All posts Embedded

View Memory Available on nanoFramework ESP32

A quick code snippet for querying internal memory on an ESP32 running nanoFramework — essential when you're working with kilobytes instead of gigabytes.

Alexander Sigler 1 min read
C#CSharpnanoFrameworkESP32
View Memory Available on nanoFramework ESP32

Once I started on the C# journey it really is hard to stop… so here I am again showcasing one of the most amazing finds in my micro controller development career: nanoFramework. This bad boy allows you to write C# code for low-level micro controllers, specifically an ESP32 in my case.

As my journey continues one of the main issues I have is keeping track of memory. I normally don’t care about it when developing a .NET Web API application, but when dealing with ESP32 controllers with KB of memory it makes a huge difference.

I didn’t find much online on how to do this, but upon browsing Discord and getting some feedback from other users (thanks @AlbertK) I have this little snippet:

using nanoFramework.Hardware.Esp32;
using System.Diagnostics;

namespace Project.Helpers
{
    public class Diagnostics
    {
        public static void PrintMemory(string msg)
        {
            NativeMemory.GetMemoryInfo(
                NativeMemory.MemoryType.Internal,
                out uint totalSize,
                out uint totalFree,
                out uint largestFree);

            Debug.WriteLine(
                $"{msg} -> Internal Mem:  Total: {totalSize}  Free: {totalFree}  Largest: {largestFree}");

            Debug.WriteLine(
                $"nF Mem:  {nanoFramework.Runtime.Native.GC.Run(false)}");
        }
    }
}

The main value you care about is nF Mem — this tells you how much memory is available to your nanoFramework application after the runtime’s own overhead.

I personally have a heartbeat service that runs every 15 seconds, toggling the internal LED and printing this call so I always know how much memory my application is consuming.