How to Code with Lua on ESP32 with XEdge32
Tags: esp32, xedge32, lua, embedded
Published: 2024-05-18 05:40:43

{% embed https://www.youtube.com/watch?v=2aunWZx-Hs0 %}

Welcome to our latest tutorial, where we dive into the powerful capabilities of the Xedge32 platform and demonstrate how to code the ESP32-S3 using the Lua programming language. Xedge32 is an advanced iteration of Xedge, designed to significantly accelerate IoT device development with its comprehensive peripheral Lua API for the ESP32. By leveraging the high-level, user-friendly Lua language, Xedge32 makes it easier than ever to integrate IoT functionality into your projects without the need for C coding.
In this tutorial, we will guide you through the steps of using Xedge32 to write scripts for the ESP32-S3, showcasing its streamlined approach to working with device components such as sensors. Whether you are new to Lua or an experienced developer, you'll find valuable insights and practical examples to help you get the most out of this powerful combination.
For more detailed information and documentation, be sure to check out the [Xedge32 documentation](https://realtimelogic.com/ba/ESP32/index.html).

## Why Use Xedge32?

- Seamless Transition to Production: Xedge32 is engineered for the smooth creation of commercial products. It offers versatile support for the various aspects of assembling a production-ready product, from building an embedded system with multiple components to embedding your final applications directly into the firmware binary. This flexibility ensures a streamlined path from development to production.
- Cost-Effective Development: In IoT development, where the expense of designing secure IoT code, the BSP (board support package), and other hardware-near software can easily reach $500, 000, controlling costs is crucial. Xedge32 addresses this challenge by significantly reducing the time and resources needed to develop secure IoT products. This efficiency translates to substantial savings, dramatically lowering overall development costs.
- Simplified Development Process: Xedge32 simplifies IoT projects by connecting Lua to ESP32's extensive peripheral features. This integration allows developers to write device-specific code in Lua, a user-friendly language, making the development process faster and more accessible.
- Speed: We recognize embedded developers' concerns when shifting from traditional C coding to the high-level Lua language. We are confident that Xedge32 will positively surprise you with its impressive speed and efficiency. Furthermore, if you have existing C code that is essential to your project, Xedge32 facilitates seamless integration. You can effortlessly include your C code in your custom Xedge32 build and access it directly from Lua, blending speed with flexibility.
- Enhanced Security: In the context of IoT, where security is paramount, Xedge32 offers a comprehensive API that facilitates secure IoT design, including easy X.509 certificate management and providing a soft Trusted Platform Module (TPM). This approach in Xedge32 simplifies the development and testing stages, ensuring secure IoT-enabled products can be developed and brought to market more rapidly and securely than traditional methods.
- Robust IoT Hub Capabilities: The Xedge32 environment, with its plethora of protocols, transforms the ESP32 into a powerful IoT, IT, and OT hub. This capability is essential for managing the interconnected nature of IoT devices and ensuring secure communication and data exchange.
- Ease of Firmware Updates: Maintaining and updating IoT devices is a significant aspect of ensuring long-term security. Xedge32 facilitates an easy OTA firmware update process, which is crucial for addressing new vulnerabilities and maintaining device security over time.
- Low-Code Programming: Xedge32 supports low-code programming using Lua, making it accessible to a broader range of developers, including those who may not have deep expertise in traditional embedded C programming. This approach drastically accelerates the development of secure IoT applications.

In conclusion, the Xedge32 development environment is a significant step forward in providing easy-to-use tools for developing secure, efficient, cost-effective IoT products. Its integration with Lua and ESP32, ease of use, and focus on security make it a compelling choice for IoT developers aiming to meet the growing demands of the IoT market.
Let's get started and unlock the potential of your IoT projects with Xedge32 and the ESP32-S3.

**Subscribe:**
[Youtube](https://www.youtube.com/watch?v=2aunWZx-Hs0)
**Support:**
https://www.buymeacoffee.com/mmshilleh

## Step 1-) Install Firmware for Xedge32

The ESP32 microcontroller stands out in the IoT realm with its dual-core 240MHz CPU, integrated WiFi, and extensive GPIOs. The low-cost and breadboard-friendly ESP32 development boards facilitate easy prototyping, allowing seamless integration with many sensors. However, the true magic unfolds with the Xedge32 IoT platform, which opens up the opportunity to program the ESP32 using the incredibly intuitive Lua programming language. The Xedge32 targets a broad spectrum of users, including those without C code experience.
With the Xedge32, programming embedded systems becomes accessible to everyone, not just embedded C/C++ experts. It's designed to simplify the development of robust, commercial IoT products, making advanced programming more approachable and affordable.
To install Xedge32 on your ESP32-S3 or ESP32-WROVER, follow these steps:
Connect the ESP32's USB cable to your computer
Click the 'Install Xedge32' button in the link below: [Install Xedge32](https://realtimelogic.com/ba/ESP32/index.html)
Upon clicking the button, a list of devices will appear in your browser. Select the device that includes 'serial' in its name and proceed with the installation wizard.
Once the installation is complete, reboot the ESP32 by unplugging and then replugging the USB cable. Your ESP32 will now be in access point mode. For guidance on configuring and using Xedge32 in this mode, refer to the [ESP32 Access Point Mode documentation](https://realtimelogic.com/ba/ESP32/source/AccessPointMode.html).


## Step 2-) Connecting in AP Mode and writing in LUA Shell

Now that we have Xedge32 loaded onto our device, we can connect and start coding! Ensure you have rebooted the device by unplugging and replugging it. This action should trigger the device to enter Access Point (AP) mode. As an access point, the ESP32 will broadcast a WiFi network that you can connect to. Simply join this network using the provided password (12345678), and you'll be ready to begin coding directly on your device.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i93ruqm3hrpc27dlw204.png)

You can see in the image above. Once successfully connected we can enter the browser based IDE by going to http://xedge32.local in our browser. You will see the following.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rulyh80t8f8ktf2l39a6.png)

We can write a simple line in the shell to print "Hello World"—a classic test to ensure our system is working properly. Open a shell from the top right corner and start typing in the HTML-based editor. (We will switch to a more robust editor once we begin writing executable Lua scripts.)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ehm3ihulydpc5x8znrq4.png)


It looks like everything is working well—congratulations! You are now programming in Lua on the ESP32 with Xedge32. Next, let's switch the device to station mode so we can connect to it while maintaining an internet connection simultaneously.
Station Mode is recommended for Xedge32 as it enables the full range of IoT features. To switch from Access Point Mode to Station Mode, follow these steps:

**Access the Lua Shell:**

1. Click the three dots (...) in the upper right corner of the Xedge editor.
2. Select "Lua Shell" to open the web-based LuaShell32.
**Program Station Mode:**
In LuaShell32, enter the following command to connect to your Wi-Fi network:

```
esp32.netconnect("wifi", {ssid="your-Wi-Fi-SSID", pwd="password"})
```

- In LuaShell32, enter the following command to connect to your Wi-Fi networ
- Replace your-Wi-Fi-SSID and password with your actual Wi-Fi credentials
**Switching Modes:**

- The ESP32 will attempt to switch from Access Point Mode to Station Mode.
- If the connection is successful, the ESP32 will remain in Station Mode.
- If the connection fails, the ESP32 will revert to Access Point Mode.
**Reconnect in Station Mode:**

- If your computer supports mDNS, reconnect to the ESP32 by navigating to http://xedge32.local/ or simply refresh the browser window.
- If your computer does not support mDNS, find the ESP32’s new IP address assigned by your router, typically found on the router’s DHCP client list page, where the ESP32 should appear as "xedge".

## Step 3-) Coding your first Lua Script

We can start coding our first Lua script by right clicking the disk in the left menu, and creating a new folder.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iyuzqih01ekvbiwcvr1q.png)

Within the folder we can create a new app (leave the default settings for now). You can name the folder/apps whatever you like


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/54zhwx52bdfsm1exp0cm.png)



Next within the app we can create an executable Lua file, {name}.xlua


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xmly57tce5h3gr6el9pr.png)


We write a simple factorial finder script to showcase some of Luas syntactical aspects.

```
-- Function to calculate factorial
function factorial(n)
    if n == 0 then
        return 1
    else
        return n * factorial(n - 1)
    end
end

-- Main code
local number = 5  -- You can change this number to calculate a different factorial
local result = factorial(number)
print("The factorial of " .. number .. " is " .. result)
```
You can copy and paste the above into the file. This script defines a recursive function factorial that computes the factorial of a given number n. It then calculates the factorial of 5 (you can modify this to any number you want) and prints the result. Once ready, we can begin to run our application,

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z7bnv55140t6uzs5qi1x.png)

Select the app config file, and check the running field,

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n441feavr5pvvxtzxlqn.png)

Now we can Save and Run our Lua script! You should see the number 120 in the console log, which is indeed the factorial of 5.

## Conclusion:
In conclusion, the Xedge32 platform provides a comprehensive, user-friendly environment for developing IoT applications with the ESP32-S3 using the Lua programming language. By simplifying the development process and integrating advanced features like secure IoT design and seamless firmware updates, Xedge32 allows developers to create robust, production-ready IoT products with ease. The high-level Lua language, coupled with the powerful capabilities of the ESP32, makes this combination an excellent choice for both novice and experienced developers looking to innovate in the IoT space. We hope this tutorial has equipped you with the knowledge and confidence to start leveraging Xedge32 in your projects. Let's continue to explore and unlock new possibilities in IoT development together.
Subscribe to our YouTube channel for more tutorials and updates, and consider supporting us on Buy Me a Coffee to help us continue creating valuable content.
Welcome to the future of IoT development with Xedge32 and the ESP32-S3!