<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Melek Chérif  on Medium]]></title>
        <description><![CDATA[Stories by Melek Chérif  on Medium]]></description>
        <link>https://medium.com/@melek_cherif?source=rss-2989411a78a4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ZU3FSIziyc7GDh4cXxOmTQ@2x.jpeg</url>
            <title>Stories by Melek Chérif  on Medium</title>
            <link>https://medium.com/@melek_cherif?source=rss-2989411a78a4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 22:36:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@melek_cherif/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[ESP32 to Kafka broker using MQTT bridge]]></title>
            <link>https://medium.com/@melek_cherif/esp32-to-kafka-broker-using-mqtt-bridge-950e6f3c0fc8?source=rss-2989411a78a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/950e6f3c0fc8</guid>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[esp32]]></category>
            <category><![CDATA[mqtt]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[iot]]></category>
            <dc:creator><![CDATA[Melek Chérif ]]></dc:creator>
            <pubDate>Fri, 24 Jan 2025 23:48:22 GMT</pubDate>
            <atom:updated>2025-01-24T23:48:22.251Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In the evolving world of IoT, managing the immense flow of data securely and reliably is becoming more and more demanding. That’s where <strong>Apache Kafka</strong> shines; it offers a scalable, fault-tolerant system ideal for robust IoT applications. Its ability to handle real-time data streams makes it a go-to solution for industries prioritizing security, resilience, and efficiency.</p><p>Often, <strong>Raspberry Pi</strong> is employed as a gateway to Kafka brokers, bridging the gap between low-power IoT devices and Kafka’s high-performance infrastructure. However, what if you could achieve this with a simpler and cheaper device?</p><p>In this guide, I’ll walk you through a practical approach to send data from an <strong>ESP32</strong> to a <strong>Kafka broker</strong> using an <strong>MQTT bridge</strong>. But first, let’s briefly compare <strong>MQTT</strong> and <strong>Kafka</strong>, two critical protocols in IoT, to understand why this method is effective.</p><h3>Requirement</h3><blockquote><strong>Hardware</strong><br>- ESP32 + sensor (Iam choosing the BNO055 IMU sensor)<br>- Local machine (I am using Ubuntu)<br>- Wifi or ethernet module</blockquote><blockquote><strong>Software<br>- </strong>IDE (VSCode with platformIO extension)<br>- Apache Kafka</blockquote><h3>MQTT &amp; Apache Kafka:</h3><h4>What is MQTT?</h4><p>MQTT (Message Queuing Telemetry Transport) is a lightweight messaging protocol designed for IoT devices with limited resources. It works on a <strong>publish-subscribe model</strong>, where devices (publishers) send messages to a central broker, and other devices (subscribers) receive only the messages they are interested in. MQTT is known for its simplicity, low bandwidth usage, and support for unreliable networks.</p><h4>What is Kafka?</h4><p>Kafka is a distributed event-streaming platform built to handle <strong>high volumes of data in real time</strong>. It stores messages in topics and processes them in sequence, making it ideal for scalable, fault-tolerant applications. Unlike MQTT, Kafka focuses on durability and data persistence, allowing messages to be replayed or processed later. This makes it a powerful tool for systems requiring reliable and long-term data handling.</p><h4>MQTT vs. Kafka</h4><p>While both are messaging systems, they serve different purposes:</p><ul><li><strong>Lightweight vs. robust</strong>: MQTT is designed for constrained devices and low-power networks, while Kafka excels in handling heavy data streams in high-performance environments.</li><li><strong>Transient vs. persistent</strong>: MQTT focuses on delivering real-time data with minimal overhead, whereas Kafka ensures data is stored and can be replayed.</li><li><strong>Ease of Use vs. Scalability</strong>: MQTT is easy to set up and works well for small IoT setups, while Kafka shines in large-scale systems requiring durability and fault tolerance.</li></ul><h3>Used approach</h3><p>The ESP32 is a brilliant microcontroller, but it can’t directly communicate with a Kafka broker because there isn’t a lightweight library designed for it, unlike MQTT, which works perfectly on devices like the ESP32. In many industrial IoT setups, Kafka is a key part of the system, thanks to its ability to handle large amounts of real-time data reliably and efficiently. By using an MQTT bridge, the ESP32 can send data via MQTT while still integrating smoothly with Kafka. It’s a practical way to get the best of both worlds when direct communication isn’t possible or the system requires Kafka.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*y9pe2sZ8dIfXxCF8cZGPJw.png" /></figure><h3>Configuration</h3><h4>PlatformIO configuration for ESP32</h4><ul><li>Install the PlatformIO extension for VSCode</li><li>Create a new project, select the board and framework, and add the necessary libraries. (The platformio.ini should be like that.)</li></ul><pre>[env:nodemcu-32s]<br>platform = espressif32<br>board = nodemcu-32s<br>framework = arduino<br>monitor_speed = 115200<br>lib_deps = <br> knolleary/PubSubClient@^2.8<br> adafruit/Adafruit BNO055@^1.6.4</pre><h4>Mosquitto broker setup</h4><pre>#Install Mosquitto<br>sudo apt-get update<br>sudo apt-get install mosquitto mosquitto-clients<br><br>#Enable and start mosquitto service<br>sudo systemctl enable mosquitto<br>sudo systemctl start mosquitto<br><br>#To check status<br>sudo systemctl status mosquitto.service</pre><h4>Kafka and zookeeper setup</h4><p>Download and install Kafka and Zookeeper from the <a href="https://kafka.apache.org/downloads">Apache Kafka website</a>. Then install Zookeeper first, because Kafka relies on it to manage its brokers.</p><pre># Start Zookeeper<br>bin/zookeeper-server-start.sh config/zookeeper.properties<br><br># Start Kafka<br>bin/kafka-server-start.sh config/server.properties<br><br>#Create a Kafka topic<br>bin/kafka-topics.sh --create --topic esp32-data --bootstrap-server localhost:9092 --partitions 1 --replication-factor 1</pre><p>A <strong>topic</strong> is a category or feed name to which messages are published; the specified address of the Kafka broker is localhost at port 9092 (to change it, you can modify the server.properties file in kafka/bin/config). A topic is divided into one or more partitions, which are the basic units of parallelism in Kafka, and in this example we only need one partition. The replication factor determines how many copies of the data are maintained across Kafka brokers (1 means no replication).</p><h3>Let’s pass to code</h3><h4>ESP32 code</h4><pre>#include &lt;Wire.h&gt;<br>#include &lt;Adafruit_Sensor.h&gt;<br>#include &lt;Adafruit_BNO055.h&gt;<br>#include &lt;utility/imumaths.h&gt;<br>#include &lt;WiFi.h&gt;<br>#include &lt;PubSubClient.h&gt;<br><br>#define BUFFER_SIZE 50                        // Buffer size<br>#define BNO055_SAMPLERATE_MS 100<br>#define SDA 21<br>#define SCL 22<br><br>int bufferIndex = 0;                          // Index for the buffer<br>unsigned long lastPublishTime = 0;<br>const unsigned long publishInterval = 500;    // Publish every 500 ms<br><br>// Buffer size and data structure<br>struct IMUData {<br>  float accX, accY, accZ;<br>  float gyroX, gyroY, gyroZ;<br>  float magX, magY, magZ;<br>};<br><br>// WiFi<br>const char *ssid = &quot;********&quot;;              // Enter your WiFi name<br>const char *password = &quot;*******&quot;;    // Enter WiFi password<br><br>// MQTT Broker<br>const char *mqtt_broker = &quot;x.x.x.x&quot;;<br>const char *topic = &quot;imu_data&quot;;      // Change to your topic<br>const int mqtt_port = 1883;<br><br>Adafruit_BNO055 myIMU = Adafruit_BNO055();<br>IMUData imuBuffer[BUFFER_SIZE];           // Circular buffer for IMU data<br>WiFiClient espClient;<br>PubSubClient client(espClient);<br><br>void initializeSensor();<br>void initializeNetwork();<br>void callback(char *topic, byte *payload, unsigned int length);<br><br>void publishIMUData();<br>void clearBuffer();<br><br>void setup() {<br>  Serial.begin(115200);<br>  initializeSensor();<br>  initializeNetwork();<br>  Serial.println(&quot;System ready!&quot;);<br>}<br><br>void loop() {<br>  // Read IMU data<br>  imu::Vector&lt;3&gt; acc = myIMU.getVector(Adafruit_BNO055::VECTOR_ACCELEROMETER);<br>  imu::Vector&lt;3&gt; gyro = myIMU.getVector(Adafruit_BNO055::VECTOR_GYROSCOPE);<br>  imu::Vector&lt;3&gt; mag = myIMU.getVector(Adafruit_BNO055::VECTOR_MAGNETOMETER);<br><br>  // Store IMU data in the buffer<br>  imuBuffer[bufferIndex].accX = acc.x();<br>  imuBuffer[bufferIndex].accY = acc.y();<br>  imuBuffer[bufferIndex].accZ = acc.z();<br>  imuBuffer[bufferIndex].gyroX = gyro.x();<br>  imuBuffer[bufferIndex].gyroY = gyro.y();<br>  imuBuffer[bufferIndex].gyroZ = gyro.z();<br>  imuBuffer[bufferIndex].magX = mag.x();<br>  imuBuffer[bufferIndex].magY = mag.y();<br>  imuBuffer[bufferIndex].magZ = mag.z();<br><br>  // Increment buffer index<br>  bufferIndex = (bufferIndex + 1) % BUFFER_SIZE;<br><br>  // Serial.print(&quot;Accelerometer: &quot;);<br>  // Serial.print(acc.x());<br>  // Serial.print(&quot;, &quot;);<br>  // Serial.print(acc.y());<br>  // Serial.print(&quot;, &quot;);<br>  // Serial.println(acc.z());<br><br>  unsigned long currentTime = millis();<br>  if (currentTime - lastPublishTime &gt;= publishInterval) {<br>    publishIMUData();                     <br>    Serial.println(&quot;Sending Buffer to MQTT broker...&quot;);<br>    lastPublishTime = currentTime;<br>  }<br><br>  // Call the MQTT client loop<br>  client.loop();<br>  delay(10);  // 10 ms delay for 100 Hz sampling<br>}<br><br>void initializeSensor() {<br>  Wire.begin(SDA, SCL, 400000);<br>  myIMU.begin();<br>  delay(1000);<br>  int8_t temp = myIMU.getTemp();<br>  myIMU.setExtCrystalUse(true);<br>}<br><br>void callback(char *topic, byte *payload, unsigned int length) {<br>  Serial.print(&quot;Message arrived in topic: &quot;);<br>  Serial.println(topic);<br>  Serial.print(&quot;Message:&quot;);<br>  for (int i = 0; i &lt; length; i++) {<br>    Serial.print((char)payload[i]);<br>  }<br>  Serial.println();<br>  Serial.println(&quot;-----------------------&quot;);<br>}<br><br>void initializeNetwork() {<br>  // Connecting to a WiFi network<br>  WiFi.begin(ssid, password);<br>  while (WiFi.status() != WL_CONNECTED) {<br>    delay(500);<br>    Serial.println(&quot;Connecting to WiFi..&quot;);<br>  }<br>  Serial.println(&quot;Connected to the Wi-Fi network&quot;);<br><br>  // Connecting to an MQTT broker<br>  client.setServer(mqtt_broker, mqtt_port);<br>  client.setCallback(callback);<br><br>  while (true) {  // Keep trying until the test message is sent successfully<br>    String client_id = &quot;esp32-client-&quot;;<br>    client_id += String(WiFi.macAddress());<br>    Serial.printf(&quot;The client %s connects to the MQTT broker\n&quot;, client_id.c_str());<br><br>    if (client.connect(client_id.c_str())) {<br>      Serial.println(&quot;Connected to the MQTT broker&quot;);<br><br>      // Send a test message<br>      const char* testTopic = &quot;imu_data&quot;;<br>      const char* testPayload = &quot;Test message from ESP32&quot;;<br>      if (client.publish(testTopic, testPayload)) {<br>        Serial.println(&quot;Test message published successfully. System is ready!&quot;);<br>        break;  // Exit the loop if the test message is sent successfully<br>      } else {<br>        Serial.println(&quot;Failed to publish test message. Retrying...&quot;);<br>        client.disconnect();  // Disconnect and retry<br>        delay(1000);<br>      }<br>    } else {<br>      Serial.print(&quot;Connection failed with state: &quot;);<br>      Serial.println(client.state());<br>      delay(1000);  // Retry delay<br>    }<br>  }<br>}<br><br>void publishIMUData() {<br>  // Variables to store the sum of the last 10 samples<br>  float avgAccX = 0, avgAccY = 0, avgAccZ = 0;<br>  float avgGyroX = 0, avgGyroY = 0, avgGyroZ = 0;<br>  float avgMagX = 0, avgMagY = 0, avgMagZ = 0;<br><br>  // Sum the last 10 samples<br>  for (int i = 0; i &lt; 10; i++) {<br>    int sampleIndex = (bufferIndex - 10 + i + BUFFER_SIZE) % BUFFER_SIZE;<br>    avgAccX += imuBuffer[sampleIndex].accX;<br>    avgAccY += imuBuffer[sampleIndex].accY;<br>    avgAccZ += imuBuffer[sampleIndex].accZ;<br>    avgGyroX += imuBuffer[sampleIndex].gyroX;<br>    avgGyroY += imuBuffer[sampleIndex].gyroY;<br>    avgGyroZ += imuBuffer[sampleIndex].gyroZ;<br>    avgMagX += imuBuffer[sampleIndex].magX;<br>    avgMagY += imuBuffer[sampleIndex].magY;<br>    avgMagZ += imuBuffer[sampleIndex].magZ;<br>  }<br><br>  // Calculate the average<br>  avgAccX /= 10;<br>  avgAccY /= 10;<br>  avgAccZ /= 10;<br>  avgGyroX /= 10;<br>  avgGyroY /= 10;<br>  avgGyroZ /= 10;<br>  avgMagX /= 10;<br>  avgMagY /= 10;<br>  avgMagZ /= 10;<br><br>  // Create a payload with the averaged IMU data<br>  char payload[128];  // Adjust the size based on your payload requirements<br>  int offset = 0;<br><br>  offset += snprintf(payload + offset, sizeof(payload) - offset,<br>                     &quot;{\&quot;AccX\&quot;:%.2f,\&quot;AccY\&quot;:%.2f,\&quot;AccZ\&quot;:%.2f,&quot;<br>                     &quot;\&quot;GyroX\&quot;:%.2f,\&quot;GyroY\&quot;:%.2f,\&quot;GyroZ\&quot;:%.2f,&quot;<br>                     &quot;\&quot;MagX\&quot;:%.2f,\&quot;MagY\&quot;:%.2f,\&quot;MagZ\&quot;:%.2f}&quot;,<br>                     avgAccX, avgAccY, avgAccZ,<br>                     avgGyroX, avgGyroY, avgGyroZ,<br>                     avgMagX, avgMagY, avgMagZ);<br><br>  // Debug: Print the payload<br>  Serial.println(&quot;Payload to publish:&quot;);<br>  Serial.println(payload);<br><br>  // Publish the JSON payload to the MQTT broker<br>  if (client.publish(&quot;imu_data&quot;, payload)) {<br>    Serial.println(&quot;IMU data published to MQTT broker.&quot;);<br>  } else {<br>    Serial.println(&quot;Failed to publish IMU data.&quot;);<br>    Serial.print(&quot;MQTT client state: &quot;);<br>    Serial.println(client.state());  // Print the MQTT client state<br>  }<br>}<br><br>void clearBuffer() {<br>  // Reset the buffer by setting all values to 0<br>  for (int i = 0; i &lt; BUFFER_SIZE; i++) {<br>    imuBuffer[i].accX = 0;<br>    imuBuffer[i].accY = 0;<br>    imuBuffer[i].accZ = 0;<br>    imuBuffer[i].gyroX = 0;<br>    imuBuffer[i].gyroY = 0;<br>    imuBuffer[i].gyroZ = 0;<br>    imuBuffer[i].magX = 0;<br>    imuBuffer[i].magY = 0;<br>    imuBuffer[i].magZ = 0;<br>  }<br>  bufferIndex = 0;  // Reset the buffer index<br>  Serial.println(&quot;Buffer cleared.&quot;);<br>}</pre><p>Ok, so let’s break this code and understand it. As I mentioned at the start, I am using the BNO055 IMU sensor as my data source, but the approach is replicable for any data type. And you can notice that the IMU sensor is heavy compared to other devices. <br>So first, we include the necessary libraries for IMU devices, WiFi, and MQTT.</p><p><strong>1. Setup function<br></strong>Initializes serial communication, the IMU sensor, and the network (WiFi and MQTT).</p><p><strong>2. Loop Function</strong><br>Reads IMU data (accelerometer, gyroscope, and magnetometer).<br>Stores the data in the circular buffer.<br>Publishes the latest IMU data to the MQTT broker.</p><p><strong>3. Sensor Initialization</strong><br>Configures the I2C communication and initializes the IMU sensor.</p><p><strong>4. Network Initialization function</strong><br>Connects the ESP32 to WiFi and the MQTT broker.</p><p><strong>5. Publishing IMU Data function</strong><br>Constructs a JSON payload with the latest IMU data and publishes it to the MQTT topic imu_data.</p><h4>MQTT bridge code</h4><pre>import json<br>from confluent_kafka import Producer<br>import paho.mqtt.client as mqtt<br><br># Kafka configuration<br>KAFKA_BROKER = &quot;localhost:9092&quot;  # Replace with your Kafka broker address<br>KAFKA_TOPIC = &quot;imu&quot;              # Replace with your Kafka topic<br><br># MQTT configuration<br>MQTT_BROKER = &quot;x.x.x.x&quot;         # Replace with your MQTT broker address<br>MQTT_PORT = 1883                # Default MQTT port<br>MQTT_TOPIC = &quot;imu_data&quot;         # Replace with your MQTT topic<br><br># Kafka producer configuration<br>conf = {<br>    &quot;bootstrap.servers&quot;: KAFKA_BROKER,<br>}<br><br># Create a Kafka producer<br>producer = Producer(conf)<br><br># Callback when a message is received from MQTT<br>def on_message(client, userdata, msg):<br>    try:<br>        # Decode the MQTT message payload<br>        payload = msg.payload.decode(&quot;utf-8&quot;)<br>        print(f&quot;Received MQTT message: {payload}&quot;)<br><br>        # Forward the message to Kafka<br>        producer.produce(KAFKA_TOPIC, value=payload)<br>        producer.flush()  # Ensure the message is sent<br>        print(f&quot;Forwarded to Kafka topic: {KAFKA_TOPIC}&quot;)<br>    except Exception as e:<br>        print(f&quot;Error processing MQTT message: {e}&quot;)<br><br># MQTT client setup<br>client = mqtt.Client()<br>client.on_message = on_message<br><br># Connect to the MQTT broker<br>client.connect(MQTT_BROKER, MQTT_PORT, 60)<br>print(f&quot;Connected to MQTT broker at {MQTT_BROKER}:{MQTT_PORT}&quot;)<br><br># Subscribe to the MQTT topic<br>client.subscribe(MQTT_TOPIC)<br>print(f&quot;Subscribed to MQTT topic: {MQTT_TOPIC}&quot;)<br><br># Start the MQTT loop to listen for messages<br>print(&quot;Starting MQTT to Kafka bridge...&quot;)<br>client.loop_forever()</pre><p>This Python script acts as a bridge between MQTT and Kafka, enabling IoT devices (like ESP32) to send data to a scalable data pipeline. Here’s how it works:</p><p>First, we set up the basics. We import the necessary libraries for MQTT and Kafka. Then, we define the configuration for both systems—Kafka’s broker <strong>address</strong> and <strong>topic</strong>, and MQTT’s broker <strong>address</strong>, <strong>port</strong>, and <strong>topic</strong>.</p><p>Next, we create a Kafka producer. This is the component that sends messages to Kafka. It’s configured with the Kafka broker address, so it knows where to deliver the data.</p><p>The heart of the script is the on_message function. This is a callback that gets triggered whenever a new MQTT message arrives. It decodes the message payload (from bytes to a string) and forwards it to Kafka using the producer.</p><p>The MQTT client is set up to connect to the broker and subscribe to the specified topic. Once everything is ready, the script enters an infinite loop, continuously listening for new messages.</p><h4>Results</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oPw7isAzV0HLnzP_xzfOYw.png" /></figure><p>The screenshot above showcases the successful streaming of IMU sensor data (accelerometer, gyroscope, and magnetometer readings) from an ESP32 device to Kafka via an MQTT bridge. Each forwarded message contains multiple sensor values. By averaging <strong>10 sensor samples</strong> before publishing, the system strikes a balance between data richness and stream efficiency. This approach reduces noise, which makes it perfect for scenarios like streaming sensor data from ESP32 devices to a real-time analytics pipeline</p><h4>Conclusion</h4><p>This project demonstrates that even <strong>heavy</strong> IMU data streams can be efficiently managed using lightweight protocols like MQTT and scalable systems like Kafka. The MQTT-Kafka bridge works seamlessly for simpler sensors (e.g., temperature, motion), making it ideal for resource-constrained IoT deployments. Kafka’s distributed nature ensures the pipeline can handle higher data volumes as more sensors (or nodes) are added.</p><h4>References</h4><blockquote><strong>Apache Kafka website: </strong><a href="https://kafka.apache.org/downloads">https://kafka.apache.org/downloads</a></blockquote><blockquote><strong>Github</strong>: <a href="https://github.com/Melek-Cherif/esp32_to_kafka_project.git">https://github.com/Melek-Cherif/esp32_to_kafka_project.git</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=950e6f3c0fc8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding IMUs: A Comprehensive Guide and Personal Journey]]></title>
            <link>https://medium.com/@melek_cherif/understanding-imus-a-comprehensive-guide-and-personal-journey-a724c0eb2d9f?source=rss-2989411a78a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/a724c0eb2d9f</guid>
            <category><![CDATA[inertial-measurement-unit]]></category>
            <category><![CDATA[motion-controller]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[sensor-fusion]]></category>
            <category><![CDATA[diy-projects]]></category>
            <dc:creator><![CDATA[Melek Chérif ]]></dc:creator>
            <pubDate>Fri, 23 Aug 2024 01:03:54 GMT</pubDate>
            <atom:updated>2024-08-23T01:03:54.970Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In this post, we will be reviewing the Inertial Measurement Unit (IMU), which is one of the most important and used modules in everyday life. Additionally, I am going to share with you my personal experience with a couple of IMUs and how to integrate them into your future projects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fWvrYbiGsva4F3ZRRMRVhw.png" /></figure><h3>What is an IMU?</h3><p>An IMU is an electronic device primarily used to track an object’s position and orientation in 3D space. It measures and reports orientation, velocity, and gravitational forces using its internal components, mainly an accelerometer and gyroscope. In some cases, it also includes a magnetometer and barometer, which work together to provide more accurate and reliable data.</p><p>Initially, IMUs were used for navigation and consisted of complex and large devices. Nowadays, with the significant advancements in technology and the rise of MEMS (micro electromechanical systems), IMUs have become more efficient and easier to integrate. That‘s why they are practically used everywhere: automotive and aerospace positioning, robotics, virtual and augmented reality, biomechanics research, smartphones, and wearable devices.</p><h4>6-axis IMU</h4><p>A 6-axis IMU combines a 3-axis accelerometer and a 3-axis gyroscope, making it the simplest and most cost-effective option. It measures linear acceleration and angular velocity, providing basic motion tracking and orientation estimation. But unlike more sophisticated IMUs, it can only precisely track motion in two dimensions (using a sensor fusion algorithm) and may experience drift over time due to its reliance only on an accelerometer and gyroscope. This leads to a decrease in orientational precision. The <a href="https://invensense.tdk.com/products/motion-tracking/6-axis/mpu-6050/#:~:text=The%20MPU%2D6050%20devices%20combine,complex%206%2Daxis%20MotionFusion%20algorithms.">MPU6050</a> is a popular example of this type.</p><h4>9-axis IMU</h4><p>A 9-axis IMU includes an additional 3-axis magnetometer alongside the accelerometer and gyroscope. The magnetometer provides magnetic data that helps correct gyroscope drift and offers absolute orientation relative to the Earth’s magnetic field. This makes the 9-axis IMU more accurate for determining orientation and heading compared to a 6-axis IMU, improving overall precision and stability in tracking movement and direction. The <a href="https://learn.adafruit.com/adafruit-bno055-absolute-orientation-sensor/overview">BNO055</a> is a good example.</p><h4>10-axis IMU</h4><p>It has an additional pressure sensor or barometer in addition to the sensors present in 9-axis IMUs. The addition of altitude measurement yields the most comprehensive motion tracking, orientation, and altitude data set and enables more thorough 3D positioning. It is currently the best choice for precise applications that require complete three-dimensional (altitude included) spatial awareness.</p><h4><strong>IMU applications</strong></h4><p>6-axis IMUs are well-suited for applications where basic motion tracking is sufficient, such as screen orientation in smartphones, gaming controllers, and simple robotics. For more advanced motion tracking and orientation needs, we have the 9-axis IMUs, making them a great choice for augmented reality (AR) devices, drones, and wearable fitness trackers. On the other hand, 10-axis IMUs are designed for high-performance applications, such as advanced drones requiring altitude data, indoor navigation systems, and precision tracking devices, making them suitable for use in aviation, automotive (including advanced driver assistance systems), and high-end robotics.</p><h3>Working principal</h3><h4>Accelerometer</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*_ZNZXAiM58CZaFmTy0cuzA.png" /><figcaption>deep dive in the internal physical system of the accelerometer [01]</figcaption></figure><p>Accelerometers serve the purpose of measuring acceleration in a single direction. So inside the tiny 3-axis accelerometer, we find 3 physical systems (along x, y and z). It consists of fixed electrodes and a flexible mass. When the sensor undergoes acceleration, the mass shifts relative to the sensor body, creating a change in the detecting element’s capacitance, piezoelectricity, or resistance. This difference can be measured and used to compute the acceleration. Capacitive sensing is mathematically dependent on capacitance fluctuation. when the plates encounter geometric changes because of the accelerating force. For parallel plates, the 𝜀 capacitance is given by 𝐶 = 𝑑𝐴 . Where 𝜀𝐴 is the permittivity of the material separating the plates multiplied by the electrode area. Then the change in the electrode position will cause a variation in the capacity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P1KKBgjp2i56GqAVE_i0Qg.png" /></figure><p>The 3-axis acc will measure the capacitance, and the output is an analog signal This signal will be converted into digital values that, in turn, will be exploitable by the system.</p><h4>Gyroscope</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*ip7ZNebJVq-61kmX9dclhg.png" /><figcaption>deep dive in the internal physical system of the gyroscope [02]</figcaption></figure><p>The accelerometers detect linear displacement, and the gyro detects the rate of change in angular displacement (angular velocity). Both sensors are manufactured using similar techniques because they have multiple similarities. When the angular velocity of the gyroscope changes, the rotor deflects, creating a change in the sensor element’s capacitance, piezoelectricity, or resistance. This difference can be measured to help calculate angular velocity.</p><h4><strong>Magnetometer</strong></h4><p>We can say that it is simply a compass because the main role of the magnetometer in the IMU is to provide the heading and add an absolute reference to the system in order to get more reliable values. Magnetometers typically work by measuring the interaction of a magnetic field with a magnetically responsive substance, such as a magneto-resistive element or a Hall-effect sensor. When put in a magnetic field, the sensor generates a voltage or resistance change that can be used to assess the field’s strength and direction.</p><blockquote>Note: Ensure that your sensor does not interfere with a close magnet or any potential magnetic field.</blockquote><h4>Barometer</h4><p>The added value from the barometer is the altitude from the surface. By measuring the air pressure, it is easy to get an accurate estimation for the altitude.</p><h3>Sensor fusion</h3><p>Sensor fusion is the process of combining data from multiple sensors to produce more accurate, reliable, and comprehensive information than could be achieved by using each sensor independently. In the context of IMUs, sensor fusion is crucial because it allows for the integration of data from accelerometers, gyroscopes, magnetometers, and sometimes barometers to provide a more precise and stable estimation of an object’s orientation, position, and movement.</p><h4>Key concepts of sensor fusion</h4><p>Sensor fusion enhances orientation accuracy by combining data from multiple sensors to correct drift, reduce noise, and provide absolute orientation. Gyroscopes, while useful for estimating orientation, tend to drift over time. By integrating accelerometer and magnetometer data, sensor fusion corrects this drift and smooths out noisy accelerometer readings. Magnetometers offer an absolute heading reference, essential for navigation.</p><p>Several algorithms support sensor fusion. The complementary filter combines gyroscope and accelerometer data, balancing short-term responsiveness with long-term stability. The Kalman Filter is more advanced, providing highly accurate estimates by filtering noise and managing uncertainty. For systems with lower computational power, Madgwick and Mahony filters offer a good balance of accuracy and efficiency, making them ideal for many IMU-based applications.</p><h3>My personal experience with IMUs</h3><p>In my continuous journey of learning embedded systems, I used IMU sensors in a couple projects, which I am going to share with you. First, I used multiple MPU sensors to make a customized motion controller programmed with ESP32 (in fact, that was my graduation internship project). After that, I used a better IMU sensor (BNO055) to study the pattern of a remote-controlled car. The common thing about using any type of IMU is that you require a minimum of theory in order to get the best possible output from the sensor.</p><h4>IMU-based motion controller</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*aT4_L5AcHadAEvOuo9mQXw.png" /></figure><p>I used both the MPU6050 and the MPU9250 with an ESP32 microcontroller to make a motion controller for a Unity game.</p><ul><li><strong>Magnetometer not found <br></strong>While working on it, I encountered one major problem. As you know, the MPU9250 is supposed to be a 9-axis IMU with an integrated magnetometer. Yet I tested more than one and all of them don’t have a magnetometer (you can verify them using the I2C scanner code within the <a href="https://github.com/hideakitai/MPU9250/blob/master/examples/connection_check_softwire/connection_check_softwire.ino">mpu9250 arduino library</a>). So, it is basically no different from the 6-axis MPU6050. To correct that, I added an external compass, the HMC 5883, hoping that I will get accurate heading information. But it didn’t go well; the result was too noisy. That is why I learned that it is better to invest in a good IMU.</li></ul><blockquote>Note: at that time and those conditions, the only available sensors were the MPU series. So I didn’t have much of a choice.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*DU-RudZavZnl2KFO34rX0g.png" /><figcaption>Circuit wiring</figcaption></figure><ul><li><strong>Calibration and configuration <br></strong>To reduce high-frequency noise and vibration for both sensors’ data, we use a low-pass filter, which improves measurement accuracy and calibration by resulting in smoother data. In my example, the defined measurement rate was 480 Hz. The MPU6050 has a programmable measurement range for both the accelerometer and gyroscope. As for the accelerometer, the used range is ± 4 g to get accurate values, and for the gyroscope, the used range is ± 1000 deg/s to also get the best possible precision. Each use case requires its own unique parameters to get the best possible result.</li></ul><pre>/*<br>Calibration function for the MPU9250<br>I am using the MPU6500 class because, without magnetometer <br>I practically have an MPU6500 sensor<br>*/<br>void Calibration()<br>{<br>  Serial.println(&quot;Position your IMU flat and don&#39;t move it—calibrating ...&quot;);<br>  delay(1000);<br>  myMPU6500.autoOffsets();<br>  Serial.println(&quot;Done&quot;);<br>  myMPU6500.enableGyrDLPF(true);<br>  myMPU6500.setGyrDLPF(MPU9250_DLPF_2);   // test with a 92Hz bandwidth<br>  myMPU6500.setGyrRange(MPU9250_GYRO_RANGE_2000);<br>  myMPU6500.enableAccDLPF(true);<br>  myMPU6500.setAccRange(MPU9250_ACC_RANGE_2G);<br>  myMPU6500.setAccDLPF(MPU9250_DLPF_2);   // test with a 92Hz bandwidth<br>  delay(1000);<br>}</pre><ul><li><strong>Sensor fusion (Complementary filter)<br></strong>Even with calibration and using the best possible rate, the sensor values are still not acceptable. As for the gyroscope, its values are acceptable only for short periods. With every movement, the error accumulates until it becomes wrong. This problem is commonly referred to as gyro drift. On the other hand, the accelerometer is reliable in the long term. So, developing a sensor fusion algorithm is the best way to overcome this problem. I used the complementary filter to combine both data and get a more stable and reliable result. But compared to more advanced sensor fusion algorithms, the complementary filter is the most basic one, and the next step of this project was to get better sensors and apply the Kalman filter.</li></ul><figure><img alt="This image presents a plot of the roll angle resulting from the gyroscope and the sensor fusion. During the first half of the plot, the system rotates from -90 to 0 frequently. The blue data is the result of the complementary filter, which, compared to the gyroscope data, is way more solid in the long term." src="https://cdn-images-1.medium.com/max/1024/1*KjpaRCwsDevt3Gc-nAL1LQ.png" /><figcaption>Estimated roll angle comparison</figcaption></figure><blockquote>This image presents a plot of the roll angle resulting from the gyroscope and the sensor fusion. During the first half of the plot, the system rotates from -90 to 0 frequently. The blue data is the result of the complementary filter, which, compared to the gyroscope data, is way more solid in the long term.</blockquote><h4>Driving Accuracy: Exploring the Power of the BNO055 Sensor in RC Car Data Collection</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YjFapbm0O_83XPLkP6Fadg.png" /></figure><p>This project came to life out of sheer curiosity shared between my brother and me. We wanted to explore the possibilities of combining our skills. Our objective was to collect IMU data from a remote-controlled car and analyze its movement patterns, ultimately aiming to develop an AI driving assistant. For the data collection, we chose the BNO055 sensor module, which offers more advanced and integrated features compared to the MPU series. The BNO055’s built-in sensor fusion simplifies calibration and configuration, making it an ideal choice for this application. If you’re looking for a practical guide on how to use the BNO055 sensor with Arduino, I highly recommend this <a href="https://www.youtube.com/watch?v=2AO_Gmh5K3Q&amp;list=PLGs0VKk2DiYwEo-k0mjIkWXlkrJWAU4L9&amp;pp=iAQB">tutorial</a> by Paul McWhorter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*Cwnv1gRk_tHTVnQMi6WO1g.png" /><figcaption>BNO055 system architecture</figcaption></figure><p>The BNO055 sensor features an additional microcontroller (MCU) dedicated to power management and running data fusion algorithms. This built-in MCU enables various operation modes, which can be configured to suit different applications. In the default mode, known as NDOF (Nine Degrees of Freedom), the sensor fuses accelerometer and gyroscope data with magnetometer readings to provide absolute orientation. This means that the end user, or programmer, receives processed and reliable orientation data without needing to perform complex calculations or data processing.</p><p><strong>Setting up the BNO055<br></strong>Similar to the MPU sensors, reading data from the BNO055 via the I2C interface requires connecting Vin to 3.3V, GND to ground, SCL to GPIO 22, and SDA to GPIO 21. After wiring, the I2C communication needs to be set up. For this project, I used the Adafruit BNO055 library for Arduino, which simplifies the process. Additionally, I utilized the sensor’s auto-calibration feature to ensure accurate data from each sensor.</p><blockquote><strong>Note:</strong> SCL and SDA pins depend on the used MCU, in my case I am using esp32 nodemcu.</blockquote><p><strong>Wrap up<br></strong>While the results didn’t turn out as we initially hoped, the experience offered valuable insights. By integrating the BNO055 into this project, we were able to remotely collect accurate and reliable orientation data, which is crucial for developing the AI driving assistant. The overall project includes additional components like Bluetooth, motor drivers, ultrasonic sensors, and IMUs, with ISR and real-time response capabilities. However, for now, let’s focus on the IMU system. The BNO055 stood out for its ease of use and advanced features, making it an ideal choice. Whether you’re tackling a similar project or simply exploring IMUs, the BNO055 is definitely worth considering.</p><h3>Conclusion</h3><p>In summary, the IMU is a versatile and essential tool in modern technology, playing a critical role in various applications, from smartphones to drones. Through working on different projects, I gained valuable insights and experience. Also, I’m considering sharing both projects separately in more detail, as I’m always open to feedback. Additionally, I plan to provide a step-by-step guide on integrating the BNO055 with the ESP32 using ESP-IDF. Finally, whether you’re just starting with IMUs or looking to deepen your understanding, I hope this post provides useful guidance for incorporating these powerful sensors into your future projects. And don’t forget to share your feedback from your different perspectives.</p><blockquote><strong>Github: </strong><a href="https://github.com/Melek-Cherif">https://github.com/Melek-Cherif</a></blockquote><blockquote><strong>references<br>1- </strong>Constantinescu, F., Gheorghe, A.G. and NIŢESCU, M., 2013. A CAPACITIVE ACCELEROMETER MODEL. equilibrium, 10, p.3.<br>2- Singh, P., Gupta, P., Srivastava, P. and Chaudhary, R.K., 2013, April. Design and modeling of MEMS capacitive gyroscope. In 2013 International Conference on Energy Efficient Technologies for Sustainability (pp. 907–911). IEEE.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a724c0eb2d9f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PWM motor control using ESP32 & ESP-IDF]]></title>
            <link>https://medium.com/@melek_cherif/pwm-motor-control-using-esp32-esp-idf-6c0e9bec4604?source=rss-2989411a78a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c0e9bec4604</guid>
            <category><![CDATA[pwm-controller]]></category>
            <category><![CDATA[c-programming]]></category>
            <category><![CDATA[esp-idf]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[esp32]]></category>
            <dc:creator><![CDATA[Melek Chérif ]]></dc:creator>
            <pubDate>Tue, 23 Jul 2024 14:30:54 GMT</pubDate>
            <atom:updated>2024-07-23T14:30:54.612Z</atom:updated>
            <content:encoded><![CDATA[<p>This article contains an efficient way to control a servo motor via pulse width modulation signal (PWM) using esp-idf as the development framework. Also, in the process, it will pass on the basics of esp32 peripherals (GPIO and timers) and readers can get familiar with esp-idf.</p><h3>Introduction</h3><p>The project was developed on a Linux machine (Ubuntu 22.04 LTS), and VSCode as the code editor.<br>ESP-IDF stands for espressif IoT development framework, which is the official IDE for espressif dev kits. It is more professional compared to Arduino and contains more features (custom build, SDK configuration, git integration). Also, you can use esp-idf directly in the terminal or as an extension in other code editors like VSCode or Eclipse. (<a href="https://github.com/espressif/vscode-esp-idf-extension">vscode extension for esp-idf</a>)</p><p>Usually, when connected to power, the DC motor rotates constantly, but for servo motors, it will stay constant, because the current in this case presents signals for the desired angle. This explains the third pin (PWM signal) of the motor that is connected directly to the esp32 GPIO. (<a href="https://www.youtube.com/watch?v=1WnGv-DPexc">More info on the servo motor working principle</a>).</p><h3>Project Architecture:</h3><h4>Hardware</h4><p>The project shows how to control a servo motor with 4 IR sensors as an input, when the sensor is ON, the motor will move toward the desired direction. Each IR sensor points to a different angle (0, 30, 60, 90). <br>This is a simplified diagram of the used wiring.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*7Kl_R1nQvr5X15FhI_kx3Q.jpeg" /><figcaption><strong>Wiring diagram</strong></figcaption></figure><blockquote>Note: if you’re using a high voltage motor (more than 5V) you should should add a driver to separate the power. Also, some IR sensors requires only 3.3V so connect them with the ESP 3V3 pin.</blockquote><h4>Software</h4><p>After installing and setting up the working environment, the first thing to do is <a href="https://github.com/espressif/vscode-esp-idf-extension/blob/master/docs/tutorial/basic_use.md">create a new project</a> using the sample project template. Now, in the project directory, you are having something like that:</p><pre>├── CMakeLists.txt<br>├── main<br>│ ├── CMakeLists.txt<br>│ └── main.c<br>└── sdkconfig</pre><ul><li><strong>main.c</strong> file is the essential file, it contains the code that will run on the microcontroller.</li><li><strong>sdkconfig</strong> is a configuration file for the esp32. In this example, the default config is already enough but in some other use cases (Bluetooth communication for example) it is possible to enable the desired modes using “idf.py menuconfig”.</li><li>CMakeLists.txt is a make file and it is required for building the project before flashing it in a target. Generally, they are generated by default but if there is a build error, checking them is the right thing.</li></ul><h3>Let’s code:</h3><h4>main.c</h4><pre>#include &lt;stdio.h&gt;<br>#include &quot;freertos/FreeRTOS.h&quot;<br>#include &quot;freertos/task.h&quot;<br>#include &quot;driver/gpio.h&quot;<br>#include &quot;esp_err.h&quot;<br>#include &quot;servo_motor.h&quot;<br><br><br>#define INPUT_PIN_1    GPIO_NUM_17  <br>#define INPUT_PIN_2    GPIO_NUM_14  <br>#define INPUT_PIN_3     GPIO_NUM_27  <br>#define INPUT_PIN_4     GPIO_NUM_25  <br>#define SERVO_PIN       GPIO_NUM_5<br><br>void setup_gpio()<br>{<br>    //configure input pins<br>    gpio_config_t pin_config;<br>    pin_config.intr_type = GPIO_INTR_DISABLE;<br>    pin_config.mode = GPIO_MODE_INPUT;<br>    pin_config.pin_bit_mask = (1ULL &lt;&lt; INPUT_PIN_1) | (1ULL &lt;&lt; INPUT_PIN_2) | (1ULL &lt;&lt; INPUT_PIN_3) | (1ULL &lt;&lt; INPUT_PIN_4);<br>    pin_config.pull_up_en = GPIO_PULLUP_ENABLE;<br>    pin_config.pull_down_en = GPIO_PULLDOWN_DISABLE;<br>    gpio_config(&amp;pin_config);<br>}<br><br><br>void app_main(void)<br>{<br>    setup_gpio();<br>    setup_pwm(SERVO_PIN);<br>    while(1)<br>    {<br>        uint8_t sensor01 = gpio_get_level(INPUT_PIN_1);<br>        uint8_t sensor02 = gpio_get_level(INPUT_PIN_2);        <br>        uint8_t sensor03 = gpio_get_level(INPUT_PIN_3);<br>        uint8_t sensor04 = gpio_get_level(INPUT_PIN_4);<br><br>        if(sensor01)<br>        {<br>            set_servo_angle(0); // Move to 0 degrees<br>            printf(&quot;Moving to 0 degrees\n&quot;);<br>            vTaskDelay(pdMS_TO_TICKS(500)); // Wait for 0.5s<br>        }<br>        else if(sensor02)<br>        {<br>            set_servo_angle(30); // Move back to 30 degrees<br>            printf(&quot;Returning to 30 degrees\n&quot;);<br>            vTaskDelay(pdMS_TO_TICKS(500)); // Wait for 0.5s<br>        }<br>        else if(sensor03)<br>        {<br>            set_servo_angle(60); // Move back to 60 degrees<br>            printf(&quot;Returning to 60 degrees\n&quot;);<br>            vTaskDelay(pdMS_TO_TICKS(500)); // Wait for 0.5s<br>        }<br>        else if(sensor04)<br>        {<br>            set_servo_angle(90); // Move back to 90 degrees<br>            printf(&quot;Returning to 90 degrees\n&quot;);<br>            vTaskDelay(pdMS_TO_TICKS(500)); // Wait for 0.5s<br>        }<br>        vTaskDelay(pdMS_TO_TICKS(1));<br>    }<br>}</pre><p><strong>Including headers</strong></p><ul><li>the “stdio.h” header file is required to include input and output functions (printf, scanf, …)</li><li>“FreeRTOS.h” and “Tasks.h” headers are included to use freeRTOS functions.</li><li>the “gpio.h” header file is required for the compiler to recognize GPIO PINs.</li><li>“esp_err.h” for logging pieces of information and error debugging</li><li>“servo_motor.h” refers to the component developed to initialize and set up the motor.</li></ul><p><strong>Define GPIOs and constants<br></strong>GPIOs can be referred to by their address explained in the esp datasheet. But to simplify things, these addresses are stored in the gpio.h header file and they are defined in this format: GPIO_NUM_XX</p><p><strong>Setup_gpio<br></strong>This function configures input pins. First, disable interrupts, then declare the mode of the pins which is INPUT. After that, attach input pins (address) to the config bit mask. and it finishes with pull-up enable and pull-down disable.</p><p><strong>App_main<br></strong>At first, there is a call for setup_gpio and setup_pwm functions to initialise input and output pins. The setup_pwm function is developed in the servo_motor component which is explained below. <br>Then there is an infinite loop (similar to the void loop in Arduino). Each iteration starts with reading sensor values. And depending on the input values we order the motor to rotate using the set_servo_angle function which is defined in the motor component. Finally, there is a delay if the motor moves the system and waits for 0.5 seconds.</p><h4>servo_motor component</h4><p>Components are used to simplify and organize code. In this project there is only one component and here is the final tree of the project after the build:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*3dsRsqOneITbfjlSl585pw.png" /><figcaption>Project directory</figcaption></figure><p>As shown in the figure, there is the c file with its header in the include folder and the CMake file to integrate the component in the build process.<br>Now let’s understand the servo_motor.h file:</p><pre>#include &lt;stdio.h&gt;<br>#include &quot;driver/ledc.h&quot;<br><br>#define SPEED_MODE      LEDC_LOW_SPEED_MODE<br>#define TIMER_NUM       LEDC_TIMER_0<br>#define DUTY_RESOLUTION LEDC_TIMER_13_BIT<br>#define FREQUENCY       50<br>#define CLK_CONFIG      LEDC_AUTO_CLK<br>#define CHANNEL         LEDC_CHANNEL_0<br>#define INTR_TYPE       LEDC_INTR_DISABLE<br><br>#define SERVO_MIN_PULSEWIDTH 1120  // Minimum pulse width in microsecond<br>#define SERVO_MAX_PULSEWIDTH 1920  // Maximum pulse width in microsecond<br>#define SERVO_MAX_DEGREE     90    // Maximum angle in degree up to which servo can rotate<br><br>void setup_pwm(uint8_t SERVO_PIN);<br><br>void set_servo_angle(int angle);</pre><p><strong>Include libraries <br></strong>First, we need the standard input/output library. Second, include the ESP-IDF library for LED control (LEDC), which provides functions for configuring and controlling PWM channels.</p><p><strong>Constants used to configure the PWM</strong></p><ul><li>SPEED_MODE: Sets the speed mode of the LEDC timer. LEDC_LOW_SPEED_MODE is used for low-speed mode.</li><li>TIMER_NUM: Specifies which LEDC timer to use. LEDC_TIMER_0 is the first timer.</li><li>DUTY_RESOLUTION: Sets the resolution of the duty cycle, which determines the granularity of the PWM signal. LEDC_TIMER_13_BIT provides 8192 levels (2^13) of duty cycle resolution.</li><li>FREQUENCY: Sets the frequency of the PWM signal to 50 Hz, which is standard for servo motors.</li><li>CLK_CONFIG: Specifies the clock source configuration for the LEDC timer. LEDC_AUTO_CLK allows the system to choose the best clock source.</li><li>CHANNEL: Specifies which LEDC channel to use for generating the PWM signal. LEDC_CHANNEL_0 is the first channel.</li><li>INTR_TYPE: Disables interrupts for the LEDC channel with LEDC_INTR_DISABLE.</li></ul><blockquote>these macros are choosed based on the characteristics of the motor retrieved from its datasheet so it can vary slightly from one to another. (<a href="https://control.com/technical-articles/understanding-the-basicsof-pulse-width-modulation-pwm/">Learn more about PWM</a>)</blockquote><p><strong>Servo motor specific macros</strong></p><ul><li>SERVO_MIN_PULSEWIDTH: Minimum pulse width in microseconds, corresponding to the servo&#39;s minimum angle (usually 0 degrees).</li><li>SERVO_MAX_PULSEWIDTH: Maximum pulse width in microseconds, corresponding to the servo&#39;s maximum angle.</li><li>SERVO_MAX_DEGREE: Maximum rotation angle of the servo motor.</li></ul><p><strong>Function prototypes</strong></p><ul><li>void setup_pwm(uint8_t SERVO_PIN): This function prototype indicates a function that will set up the PWM signal on the servo pin. It will configure the LEDC module with the parameters defined by the macros.</li><li>void set_servo_angle(int angle): This function will set the servo motor to a specified angle.</li></ul><h4>servo_motor.c</h4><pre>#include &quot;servo_motor.h&quot;<br><br>void setup_pwm(uint8_t SERVO_PIN) {<br>    // Configure the LEDC timer<br>    ledc_timer_config_t ledc_timer = {<br>        .speed_mode       = SPEED_MODE,<br>        .timer_num        = TIMER_NUM,<br>        .duty_resolution  = DUTY_RESOLUTION,<br>        .freq_hz          = FREQUENCY,<br>        .clk_cfg          = CLK_CONFIG<br>    };<br>    ledc_timer_config(&amp;ledc_timer);<br><br>    // Configure the LEDC channel<br>    ledc_channel_config_t ledc_channel = {<br>        .speed_mode     = SPEED_MODE,<br>        .channel        = CHANNEL,<br>        .timer_sel      = TIMER_NUM,<br>        .intr_type      = INTR_TYPE,<br>        .gpio_num       = SERVO_PIN,<br>        .duty           = 0, // Initial duty cycle<br>        .hpoint         = 0<br>    };<br>    ledc_channel_config(&amp;ledc_channel);<br>}<br><br>void set_servo_angle(int angle) <br>{<br>    // Convert angle to duty cycle<br>    int pulsewidth = SERVO_MIN_PULSEWIDTH + ((SERVO_MAX_PULSEWIDTH - SERVO_MIN_PULSEWIDTH) * angle) / SERVO_MAX_DEGREE;<br>    int duty = (pulsewidth * 8192) / 20000; // 8192 is 2^13 for 13-bit resolution<br>    ledc_set_duty(SPEED_MODE, CHANNEL, duty);<br>    ledc_update_duty(SPEED_MODE, CHANNEL);<br>}</pre><ul><li>The setup_pwm function sets up the PWM configuration, it takes the gpio PIN and configures it as an output with analog signal. This function is also needed for a DC motor or any analogue actuator.</li><li>The set_serv_angle function adjusts the servo motor to the specified angle by calculating and setting the appropriate PWM duty cycle. (convert from angle to pulse width, then from pulse width to duty cycle)</li></ul><blockquote><strong>Github link:</strong> <br><a href="https://github.com/Melek-Cherif/motor_control_esp32/tree/main">https://github.com/Melek-Cherif/motor_control_esp32/tree/main</a></blockquote><blockquote><strong>References:<br></strong><a href="https://github.com/espressif/vscode-esp-idf-extension">https://github.com/espressif/vscode-esp-idf-extension</a></blockquote><blockquote><a href="https://www.youtube.com/watch?v=1WnGv-DPexc">https://www.youtube.com/watch?v=1WnGv-DPexc</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c0e9bec4604" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>