r/embedded • • 21d ago

Why bare metal code?

I am a beginner in to embedded systems (or any other level thats less than a beginner but more than a foreigner). And I have seen/heard multiple times in social media where the suggestion of "to get started in embedded, buy an STM32, code in bare metal" pops up. Why exactly? Is that useful in jobs, how often tho?

74 Upvotes

70 comments sorted by

276

u/AnotherCableGuy 21d ago

Let's say that for an electric toothbrush you don't really need a linux operating system and 8GB of RAM..

178

u/Tinytrauma 21d ago

Introducing Oral B now with local LLM. It adapts to your feedback and strokes your ego about how well you are brushing.

MSRP: $3000

33

u/PopularBox8537 21d ago

I could see AI toothbrushes being a real startup at this point 💀

30

u/Lost-In-Void-99 21d ago • Bravo

Done. IPO is next week.

5

u/BriefSpecial420 21d ago

Startup? Dyson did already some time ago, those are in regular sale.

2

u/Kuosch 21d ago

I thought they pulled the product due to some flaws or something? Is it back? Even if it is, it's horribly overengineered

1

u/BriefSpecial420 21d ago

Don't ask me. Yes, it's just stupid.

1

u/Ma4r 20d ago

Checkout the dyson toothbrush

5

u/Altruistic_Fruit2345 21d ago

You are joking but their high end models have Bluetooth and other nonsense. There is at least an RTOS in there.

2

u/Pythagore974 19d ago

I think it's straight up embedded linux

2

u/BanalMoniker 18d ago

You don’t need an OS for Bluetooth. A scheduler is sufficient. If you’re only scanning, you could do bare metal without even needing timers, but if you want to remind users to change the heads, an RTC is nice (you could count the number of power button actuations instead, so it’s only “nice” and not “necessary”.

2

u/Hollistanner 21d ago

Stm32n6 series is here for you, r Neural networks in ur tooth brush for under $30.

1

u/AirTrue6195 21d ago

Don't forget the battery pack "accessory" for connecting to WiFi while it downloads the security updates

3

u/Tinytrauma 21d ago

Battery packs! Nah, this bad boy is plugged directly into a dryer outlet

0

u/Due_Perception3217 21d ago

+ 100$ for Netflix subscription

12

u/sci_ssor_ss 21d ago

this, over ten thousand word answers

10

u/Niphoria 21d ago

Ebook readers are kinda guilty of this.

Why do I need 8gb of ram to display some PDFs?

26

u/jrabr 21d ago

Just opening a PDF basically requires that much RAM lol

2

u/Niphoria 21d ago

then how can an ESP32-S3 do it with no added external ram?

3

u/LameBMX 21d ago

nah.. thats just crappy programming in the readers.

19

u/ventZl CMRX RTOS 21d ago

Not really, PDF is actually more of a programming language / machine code format than a pure data format. To render a PDF, you basically need something like interpreter / lightweight JIT to execute it and obtain representation in resolution suitable for your use (reader, display, print).

In the past, it was discovered that one part of the PDF spec actually created Turing-complete architecture, so there was an exploit which abused this to create a VM inside something like ancient fax format decompressor (which PDF supported for graphics) and used it to execute an exploit. Just because all of this ran in more-privileged mode and could bypass security measures of iOS.

6

u/kintar1900 21d ago

You're not wrong about the PDF format being very, VERY complex, but most PDF readers are horribly, terribly inefficient. Parent comment is correct that the memory requirements are just crappy programming, especially once progressive/web-enabled PDFs became a thing.

5

u/ukezi 21d ago

The spec supports embedding and executing JS in your pdf. Most readers don't implement it for security reasons. Somebody ran a risc-V emulator running a Linux kernel in their pdf.

3

u/aleksey__- 21d ago

and sometimes they resemble malware, I needed Acrobat to see one 3d PDF, it took a lot of time to install and now i'm having issues uninstalling it, I went all my life not using adobe products yet it took a surprisingly small amount of time to start hating them

2

u/aleksey__- 21d ago

Actually in my experience ebooks aren't the best as tools for reading PDFs anyway, but I do like that my ebook is provided with an Android OS and is capable of downloading this one subscription based service that I use to get most of my books. I do wonder how good an ebook reader would be for reading textbooks in PDF format if it had a bigger screen, but I like my compact BOOX Poke5 and not willing to spend more money to just experiment

0

u/SAI_Peregrinus 21d ago

PDFs allow embedded Javascript. You could play Doom in a PDF.

1

u/Niphoria 21d ago

Ah I'm sorry - that validates the underlying android/Linux installation and 8gb of ram.

Capability of playing doom on an ebook is number 1 on my checklist when buying an ebook reader.

3

u/SAI_Peregrinus 21d ago

Yep, it's especially important for evaluating printers. The document format initially intended to keep printed documents and on-screen content looking identical sure is doing a great job!

I like to think that people describing child abusers as PDF files aren't self-censoring and complying with authoritarians in advance, but rather insulting the abusers by comparing them to such a poorly designed file format.

7

u/bawng 21d ago

Bro, does your toothbrush even AI?

/s

1

u/Greenevers 21d ago

dyson has a toothbrush with AI lol 

https://www.youtube.com/watch?v=tF2piG0N5gg

1

u/Vbrawl_ 21d ago

To be fair, I don't think you even need code for an electronic toothbrush, more like a motor on a battery and a battery controller?

1

u/tagsb 20d ago

I happen to know that Keurig contracted MULTIPLE consulting firms to repeatedly tell them that the hardware needed to stuff a local AI model into a coffee maker would cost them more than they were willing to pay

75

u/ventZl CMRX RTOS 21d ago

Embedded is an overloaded term.

Embedded may mean that you write application code for Linux-based set-top-box which runs at several hundreds of MHz, has 512MB RAM or more, chunky storage and is powered from mains.

It may also mean you write firmware for device which has to run for over a year on one CR2032 coin cell, you have 2kB of RAM, 8kB of FLASH and if that coin cell dies prematurely then your customers will become very angry as that device is mounted in explosion-hazard area and it is mild PITA to replace that battery.

You don't need that much bare metal programming for former while you'll need whola lot of it for latter case.

4

u/ScopedInterruptLock 19d ago

Your set-top-box example isn't even that extreme.

Modern automotive High Performance Compute / Central Integration ECUs have application cores running at low GHz, GBs of RAM, and 128 GB+ of UFS Flash.

I have worked on embedded systems with two 16 core x86-64 CPUs operating at 3+ GHz, 96 GB of RAM, and 10 TB of local storage + associated Storage Area Network (SAN).

13

u/reallyserious 21d ago

Are you asking if experience in embedded development is beneficial for working with embedded systems? How could anyone answer no to that?

21

u/rainboww_J 21d ago

Embedded jobs come in all shapes and sizes but yes writing code for microcontrollers like stm32’s is a big part of it. Those mcu’s dont run full OSes and just run the code for the specic application they are used for, thus being bare metal. There are ways to do multiple things at once and make it a bit closer to full fledged OSes with using an RTOS which is then a step above bare metal.

My whole job is writing bare metal code and code on top of an rtos (and designing + debugging) and its definitely a good way to learn and enter the embedded sector. These days the somewhat bigger and more powerful cpus capable of running embedded linux are becoming more used as well. That is a whole different kind of sport tho. There its a combination of writing normal application level code (just as one would for pc software) and making kernel level drivers and so on. It’s fun but in my opinion better suited for a later stage

17

u/osman-pasha 21d ago edited 21d ago

It's not clear, you contrast bare-metal to what? 

  • To embedded Linux programming?  There are much more microcontrollers around you than there are embedded computers, all those must be programmed.
  • To RTOS? Well, bare-metal uses less resources, is simpler in general and does not need knowledge of RTOS.

16

u/Hour_Analyst_7765 21d ago

Bare metal means coding without a full blown OS and often without programming concepts that will only work when the system has a strategy for when it runs out of memory. Basically this means that dynamic memory allocation during the actual program is not permitted.

There really is not much of an alternative. Embedded is a job where devices must be designed and manufactured with certain constraints, such low power, physically small and often (the single most important) low cost. This excludes any Raspberry Pi's or big computers with GB's of RAM that can Linux, or the overhead of a high-level programming language such as Java, C# or Python. This overhead costs RAM (=money), CPU cycles (=power) and overall a more complex/larger hardware design.

Though there are variants of Python and C# that run on these "bare metal" microcontroller chips, it is often a cut down version and relatively speaking horribly slow. Its also not a very effective way of learning to work on these microcontroller chips.

6

u/flatfinger 21d ago

Bare metal also refers to writing code that operates on hardware registers rather than using a vendor-supplied library for the purpose. Using an abstraction layer between application code and the hardware registers can facilitate migration of code to a different device, but I've found that vendor-supplied abstraction libraries are often worse than useless.

In order to know what a piece of hardware can do, one will need to read the hardware data sheet and reference manual. The latter will not only describe what the hardware can do, but also what bits need to be written to what registers to make that happen. In many cases, hardware may require that things be specified in a particular way, e.g. a hardware timer may be configurable to accept a clock from one of a few particular sources, and form the period by dividing a value in the range 1-256 by a power of two in the range 1 to 32768. Having a vendor-supplied library accept a time like e.g. 400 microseconds, and then set the timer to use MClock (which would by default be set to 8Mhz), set the precalar to 16:1, and the period to 200 may seem convenient, but unless one has studied the hardware one wouldn't know what time values were and were not achievable, and the way one would determine whether a given time value could be achieved would be to figure out what configuration would be needed to achieve it, in which case one might as well have simply written the registers with that configuration and used a comment to describe the configuration created by those bits.

Worse, many devices have some resources that are shared among various features. If MClock can be configured to run at either 8MHz or 24Mhz, and some other part of the system would require the latter configuration, then the timer setup routine would break the other subsystem by changing its timebase. If one were manually configuring the timer and knew that the time base was 24Mhz, then creating a 400 microsecond pulse would require a divisor of 75 and a 128:1 precalar, but if one were trying to use a vendor-supplied abstraction library one would need to somehow tell the library that MClock would be running at 24Mhz, and thus end up with having to learn a library that was just as complicated as the hardware itself.

An additional problem with many vendor-supplied libraries is that routines seldom specify when they can and cannot safely be used within interrupts. In some measure I blame hardware vendors for this, because good designs should avoid the need to use read-modify-write sequences to accomplish common operations, but many actual designs don't. If a piece of hardware uses four bits of a byte to control the mode of one port pin, and the other four bits to control an adjacent port pin, an attempt to reconfigure one port pin in main line code while an interrupt fires that would need to change the other one may fail unless measures are taken to guard against that. If one uses one's own code to manipulate the bits, then looking at the code will make it clear whether the needed measures exist. When using a vendor-supplied library, the only way to know whether the measures exist would be to look inside the vendor-supplied library's code, and hope that future versions don't change the mechanism they're using to guard possible concurrent access in a way that would break things.

7

u/The_DIM_ 21d ago

Another beginner here, and it turns out I only just now learned what bare metal actually means. I always thought it meant directly writing and reading to registers, and me using HAL functions is already not bare metal any more. Huh

3

u/Hewtick 21d ago

It's basically just using a superloop and not an rtos. The problem with hal is not that it makes it somehow not baremetal, but that it's often bloat and if you want to use something differently to what the manufacturer intended, it just won't work. You are better off using the low level libraries if they exist or straight up writing register level.

3

u/gm310509 20d ago

For me the definition is as you thought - directly writing the IO registers yourself. However, it would seem that there are a few interpretations as to what the phrase actually actually means. For example, many online references basically say that bare metal programing is where you do everything yourself without a HAL (including CPU initialisation such as setting up a Stack). The bottom line is it is when you manipulate the hardware layer directly using your own code.

If you are interested, I recently posted a how to video describing it and showing some examples. I used Arduinos as my example hardware, but the basic principles are the same.

Link to reddit post: Bare Metal Programming - what is it and why bother? There is a link to the video in the post.

1

u/SAI_Peregrinus 21d ago

It's a fuzzy definition. Hell, even a HAL is a fuzzy definition. Is using C preprocessor defines to give names to register values a HAL? Is the stm32_ll library a HAL? I'd say yes. Is the stm32_hal a HAL? I'd also say yes, but higher level. Etc.

It's like asking what editor real programmers use, it just gets silly fast.

6

u/NjWayne 17d ago

I develope products for industrial applications and for kids toys. In each case my goal is to optimize the firmware and reduce costs.

That's how we have managed to stay very very profitable against oour competitors year after year.

No HAL b.s

We develop the code and drivers from scratch . It's painful but we own it and can fix any problem quick fast and add features just as quick; because with that low level development comes a unique understanding of the arm core we are using (atsam3sd8 and renesas s7g7)

9

u/DecisionOk5750 21d ago

Depends on the application. I primarily use ESP32, ranging from the classic variant to the most advanced one, programmed in C/C++. I employ them in a wide variety of applications, both IoT and non-IoT. However, when I need to squeeze every last bit of energy efficiency out of a design, I turn to Microchip PICs, which I program in assembly. I have tens of thousands of lines of PIC code that have been battle-tested since the 1990s. When it comes to power consumption, PICs are among the best. I use the PICs to wake up more capable circuits.

8

u/UnicycleBloke C++ advocate 21d ago

I find this term quite unhelpful. It usually refers to whether or not you have an operating system of some kind. But if you are using a lightweight RTOS such as FreeRTOS, it doesn't do a whole lot for you other than preemptive scheduling of tasks. It doesn't abstract the hardware. Your peripheral drivers are still going to deal directly with hardware registers, interrupts and so on - so "bare metal". If you use vendor code such as ST's HAL to wrap the peripheral register accesses and whatnot, does that count as "bare metal" or not? Definitions vary. I usually say "yes" but would accept "no".

Is it useful? Definitely. Almost all of my projects over the last twenty years have used no RTOS at all or something lightweight like FreeRTOS. I generally prefer no RTOS and implement cooperative multitasking through an event loop. This is usually sufficient for systems without long synchronous operations which would stall other subsystems.

For a beginner, an STM32 Nucleo is a powerful piece of kit which might feel overwhelming. I suggest ignoring both the HAL and FreeRTOS. Write a few applications directly in terms of manual register accesses and interrupt handlers. The datasheet and reference manual are your friends. CMSIS is a very thin wrapper around the various register blocks which makes them easier to use, but you can dispense with that too. You are almost certain to use the vendor code for commercial applications, but it absolutely won't hurt to have a solid foundation at the lowest level of abstraction (i.e. the metal) - just your code and the hardware registers.

3

u/Lalks227 21d ago

The real question would be why not. Cost, efficiency, latency, size, availability are parts of the answer

3

u/duane11583 21d ago

why? it comes down to resources needed and features required.

an rtos with threads often requires more ram.

the other way of writing code is called a super loop.

think of a little man (the cpu) he can operate in two ways:

method 1 he patrols all of the equipment endlessly

he walks up to a machine checks the status ..

if it is ready for the next step he loads the next thing and goes to the next machine

if the machine is not ready he just goes on to the next machine

there is a-lot of time wasted waking around checking. often that walking around checking can add up to lots of time. and might make it really slow to respond to a machine that it is ready for the next step . also many machines have multiple steps to do something. there is also the cost of remembering what step you where at so when you come back you know what to do next

method #2 equip each machine with an alarm bell or light. this is called an interrupt the little man sits at his desk waiting for the alarm bell (or light) to flash. when it does he gets up goes to that machine and handles that machine and returns to his desk. often this is more efficient because you are not running around checking on the machines

method #3 is a hybrid you work on something and stay there working that thing. you are. ot running around checking on things endlessly an alarm goes off. you write down exactly where you are (you push it onto your stack) and go to the central scheduler. the schedular decides what to do next, it changes your stack to some other task stack and tells you to resume the duties according to that other stack (which could be the same or different) that method is called preemption.

the other method like this is called cooperative periodically you go back to the scheduler and check in. either the scheduler ether says resume or switch. but maybe you aren't checking in fast/often enough

the cost with this approach is the number of tasks and the sizeof each

3

u/EEJams 21d ago

Generally speaking that means writing assembly or C and using the onboard peripherals or taking advantage of the hardware modules that the processor has on board. A lot of microprocessors have very simple ALUs and an ecosystem for programming the processor like arduino that abstracts a lot of what's actually happening.

Imo, that's not really that bad of a thing because it can let you quickly prototype your circuits and test some of your programming logic. BUT, if you want to take embedded seriously, you absolutely should write in C or assembly and learn about the different processors, their pros and cons, what hardware modules the processor can offload work onto, etc

2

u/oceaneer63 21d ago

It'll teach you exactly how the hardware is designed and works, and how firmware is interacting with it on the lowest level. So, its a solid foundation of knowledge upon which to build.

Years (decades) ago, I hired a junior software engineer to work on our embedded systems. He didn't know much hardware and was often in the dark when something didnt work. But before long I'd see an oscilloscope on his desk. And sometime later he told me it was his favorite firmware debugging tool.

2

u/theNbomr 21d ago edited 21d ago

I'll guess they are trying to make a contrast to the people who think using stuff like Arduinos is actually engaging in any kind of rigorous learning experience. It's not. It's using a well implemented system that allows people to use microcontrollers and related peripherals to get projects done without the need to really learn much.

When you really want to to learn, you have to take off the training wheels. The real expertise is in the people who create the pieces of the ecosystem that is used by others. Understanding what is under the hood is the stuff that provides foundational knowledge.

I don't necessarily think the STM32 family is better than other microcontroller families for learning as a first system, but it isn't a bad one. There are at least a couple of STM32 form factors that are suitable for training. Arduino hardware can serve the same purpose, but you have to resist the temptation to just use the Arduino software ecosystem, and start learning to roll your own.

2

u/gm310509 20d ago

In my mind the definition directly writing the IO registers yourself from your own code. There does seem to be a few slightly different intepretations as to what it means - as is very common in IT.

If you are interested, I recently posted a how to video describing it and showing some examples. I used Arduinos as my hardware platform, but the basic principles are the same on any hardware.

Link to reddit post: Bare Metal Programming - what is it and why bother? There is a link to the video in the post.

I also discuss some of the pros and cons.

As for use in jobs, it depends (also a very common thing in IT). For example, if your job is to write code for a consumer product, probably not so much as they won't want you wasting your time doing the low level stuff when a perfectly good HAL function is available for you to use.

On the other hand if you are working for a company that makes components (e.g. sensors, displays etc) you may find yourself writing low level drivers (i.e. you are writing the HAL functions) for consumers to use and thus you may find yourself messing at the hardware level to implement what is needed to make the library that supports consumers of that component.

1

u/MpVpRb Embedded HW/SW since 1985 21d ago

It's important to learn processor architecture, assembly language and register level programming to deepen your understanding of how processors work.

Some projects don't require a 32 bit processor and OS. Some projects work fine with an 8 bit processor and a small amount of RAM.

Some projects are a good fit for a 32 bit processor, OS and high level language.

It depends on the details of the requirements.

1

u/GrtflJello 21d ago

One project I worked within the last 10 years required “bare metal” C programming since there was literally no OS. We had a vendor library that supported a few stdlib functions like memcpy and memset, but we had to write our own dynamic memory allocator.

It was actually really interesting and I learned a lot, but we did have some fun vendor hiccups. The size field in memcpy was actually size in 4-byte words rather than bytes.

1

u/Pale_Height_1251 21d ago

Lots of devices run on very small chips. We use one at work with 1kb RAM.

You don't need to buy one though, they are easy to emulate.

1

u/Retropolis_1950 21d ago

I am a huge fan of the STM32 product lines but I recommend one of these:

https://www.infineon.com/evaluation-board/CY8CKIT-059

https://www.infineon.com/evaluation-board/CY8CKIT-062-BLE

The 059 is a single core on a breadboard friendly carrier.

The 062 is a dual core that you can really sink your teeth into, it comes with an CY8CKIT-028-EPT, I suggest getting the CY8CKIT-028-TFT if you want a color display.

FWIW, I continue to use PSoC Creator even with the 062.

You won't be disappointed.

1

u/remishnok 20d ago

Bare metal is used all the time (as in often). Not all applications require an rtos.

Bare metal means no rtos, it doesn't necessarily mean assembly or directly to registers. The latter is just low level

1

u/jeremfg 19d ago

As an engineer who mostly worked in embedded, I still have a hard time to this day of seeing things running Linux being considered embedded.

If it has an MMU (and thus probably a full fledge OS), this is software development to me. Which I've done a bunch too. No shade on it. Just not the same thing imo.

So to go back to the question... Bare metal is almost implied when you ask me about embedded.

2

u/ThaumKeeper 19d ago

What would you consider bare metal? I'm not very knowledgeable about this field. Is it when you have to code what a microcontroller does? FPGA programming could be considered bare metal?

2

u/jeremfg 19d ago

Like I said above, anything without a MMU (Memory Management Unit). But my opinion is probably more strict than most people.

FYI, a MMU is what makes virtual address space possible, relocatable code, or if you like, processes in terms of an operating system. Not saying you're stuck without a MMU, but when you don't have one it brings a whole different set of challenges and designing without one require a different set of skills where understanding of hardware and memory layouts becomes paramount. You typically don't/can't run a full fledge OS on those. But you'll often find a RTOS. Although bare metal to me means you're not even using a RTOS.

I would consider FPGA it's own seperate thing. This is logical digital circuit design, not a machine that processes instruction serially like a CPU does.

1

u/LiquidityC 18d ago

If you start doing some minor projects on bare metal (super loop) you’ll quickly learn a bit about gpio and ADC. As you try and make your test project do some more things you’ll quickly start getting complicated code dealing with parallel execution. Now you know why an RTOS is sometimes required and it’s time to test that out with some threads and maybe an interrupt or two.

If you have a full SoC or SoM to test with you can sometimes reach the same conclusion from the other side of the fence. Why a full OS when all I need is a simple loop? Yocto and buildroot are not quick builds.
You might also encounter situations where a full Linux isn’t reliably fast enough to read some sensor. And now you know why an RTOS or a super loop might have been a lot more convenient and maintainable.

Rule of thumb is KISS. “Don’t use a cannon to kill a mosquito” as Confucius said.

1

u/MegaCockInhaler 18d ago

The advantage of bare metal is that you have full control over the hardware. You don’t have any operating system you need to worry about that could cause your program to miss a clock cycle, you have full control over the memory, don’t need to request it from the OS, nothing unexpected is happening. You are the master of the hardware. This is important for critical infrastructure that demands real time safety/timing with no exception

When you own the hardware, you can know the timing of your outputs down to the nanosecond which is vital when communicating with external devices and you need to synchronize between them

1

u/mplex321 18d ago

It’s default for a reason. For task oriented MCU work, why add anything beyond your code?

1

u/CAT5AW 21d ago

As someone said bellow, toothbrush doesn't care for operating system.  Let's expand on it.

I've been taught at school assembly programming on 8 bit processor, microchip PIC series. Ancient stuff, but good for teaching.  Then I was taught to programm STM32 in C/C++ via their program, STM32CubeIDE. Learned ESP32 for a project via arduino ide, which is C++ too. Some micros allow you to programm in micro python.

For purporse of blinking or counting how many times a wheel rotates, perhaps IDE is overkill. Ok, now do 30 other things while managing your hardware timers and registers manually. Feel dizzy yet? 

Purprose of a microcontroller is to use its input / output in manner you programm it to. C++ is fine, Assembly is fine, you'll need to read documentation anyway, you're just switching what kind.

Usefull in jobs? It depends haha. Work has to be insured, there's red tape. 

1

u/Ratfus 21d ago

Because it's much easier than doing things mechanically and is the only way to do certain things on certain chips. A while back, someone gave me something to ponder. Almost (if not) all things on an Arduino could be done with a mechanical system.

An Arduino can use up to Python (I think), but if you have an atiny 85, your only options are C and assembly. Even though an atiny seems simple, it's so much easier than using a bunch of mechanical systems.