<?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 Erick Andrés Obregón Fonseca on Medium]]></title>
        <description><![CDATA[Stories by Erick Andrés Obregón Fonseca on Medium]]></description>
        <link>https://medium.com/@erickof?source=rss-1615d8d84c36------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*D4fUL6j2pwch-dY7</url>
            <title>Stories by Erick Andrés Obregón Fonseca on Medium</title>
            <link>https://medium.com/@erickof?source=rss-1615d8d84c36------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 11:39:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@erickof/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[Where Consciousness, Biology, and Quantum Physics Meet: Orchestrated Objective Reduction by…]]></title>
            <link>https://erickof.medium.com/where-consciousness-biology-and-quantum-physics-meet-orchestrated-objective-reduction-by-93dba7dc8369?source=rss-1615d8d84c36------2</link>
            <guid isPermaLink="false">https://medium.com/p/93dba7dc8369</guid>
            <category><![CDATA[quantum-physics]]></category>
            <category><![CDATA[consciousness]]></category>
            <category><![CDATA[biology]]></category>
            <category><![CDATA[physics]]></category>
            <category><![CDATA[brain]]></category>
            <dc:creator><![CDATA[Erick Andrés Obregón Fonseca]]></dc:creator>
            <pubDate>Tue, 03 Nov 2026 06:01:40 GMT</pubDate>
            <atom:updated>2026-11-03T06:01:40.422Z</atom:updated>
            <content:encoded><![CDATA[<h3>Where Consciousness, Biology, and Quantum Physics Meet: Orchestrated Objective Reduction by Penrose/<em>Hameroff</em></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qvC1QA1vFxutGF-vNeB_hQ.png" /><figcaption>Image generated by ChatGPT to illustrade the concept.</figcaption></figure><p>In 2026, I started exploring and expanding my scientific knowledge through books. My reading list included Javier Santaolalla’s <em>El bosón de Higgs no te va a hacer la cama</em> (<em>The Higgs Boson Is Not Going to Make Your Bed</em>) and <em>Inteligencia física</em> (<em>Physical Intelligence</em>), Carlo Rovelli’s <em>Seven Brief Lessons on Physics</em> and <em>White Holes</em>, and Benjamín Labatut’s <em>When We Cease to Understand the World</em>, among others. Along the way, one question caught my attention: <strong>Could quantum physics help explain consciousness?</strong></p><p>One proposed answer comes from physicist Roger Penrose and anesthesiologist Stuart Hameroff. Their hypothesis is called Orchestrated Objective Reduction, or Orch OR. It suggests that consciousness arises from quantum processes within microtubules — tiny structures inside our neurons — involving a proposed form of quantum-state collapse. It attempts to connect brain biology with fundamental physics. <a href="https://doi.org/10.1016/j.plrev.2013.08.002">Penrose and Hameroff describe the proposal in their review of Orch OR</a>.</p><p>But how could events at such a tiny scale contribute to the experience of being aware? To understand their proposal, we first need to unpack its unusual name — and the roles that biology and quantum physics play in it.</p><h3>Unpacking Orchestrated Objective Reduction</h3><p>The name sounds intimidating, but it brings together two ideas: a proposed physical process called <em>objective reduction</em>, and the biological activity that would <em>orchestrate</em> it.</p><p>Let’s start with the physics. In quantum mechanics, a system can exist in a <em>superposition</em>, a combination of alternative states that can interfere with one another. How this description relates to the single outcome recorded in a measurement is part of the quantum measurement problem.</p><p>Penrose proposes that gravity could play a role in resolving this puzzle. Different arrangements of mass correspond to different geometries of spacetime. In his proposal, a superposition involving those different geometries has a limited lifetime and eventually collapses into one outcome. This is called <em>objective reduction</em> because the collapse would occur as a physical event, independently of anyone observing it. Gravity’s role in this process is a hypothesis. Penrose developed the argument in “<a href="https://doi.org/10.1007/BF02105068">On Gravity’s Role in Quantum State Reduction</a>.”</p><p>The word <em>orchestrated</em> brings biology into the picture. Hameroff identified <em>microtubules — </em>hollow structures built from a protein called tubulin — as a possible setting for the relevant quantum processes. Microtubules are established components of the cell’s internal framework. Orch OR proposes an additional role: supporting quantum activity that cellular processes could organize and influence. <a href="https://hameroff.arizona.edu/research-overview/orch-or">Hameroff describes this proposed role in his research overview</a>.</p><p>The central claim is that these biologically organized quantum processes would undergo objective reduction — and that such events would constitute moments of conscious experience. In this picture, the brain’s biology would help shape those moments. <a href="https://doi.org/10.1016/j.plrev.2013.08.002">This connection is set out in Penrose and Hameroff’s review of Orch OR</a>.</p><p>That is the crucial step requiring evidence: connecting a proposed physical event to the experience of being aware. Understanding why they chose microtubules is the next part of the story.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rK8Ou1zklFiwddeJRs7p6Q.png" /><figcaption>Image generated by ChatGPT to illustrade the concept.</figcaption></figure><h3>Inside the Neuron: Why Microtubules Matter</h3><p>A neuron contains an elaborate internal structure. Part of that structure is its <em>cytoskeleton</em>, a network of protein filaments that helps organize the cell. Microtubules belong to this network, with tubulin proteins assembled into repeating patterns that form hollow tubes.</p><p>One of their established functions is to provide tracks for transportation. Molecular motors — including a protein called <em>kinesin — </em>move cargo along microtubules. Imagine a microscopic railway carrying materials through the cell. <a href="https://doi.org/10.1016/s0092-8674(85)80099-4">Experiments identifying kinesin demonstrated this transport mechanism</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m2Gya-Jj_bWHZi30eZfDLg.png" /><figcaption>Image generated by ChatGPT to illustrade the concept.</figcaption></figure><p>For Hameroff, the organized arrangement of tubulin raised another possibility: could these structures also process information? Orch OR proposes that interactions among components of tubulin could support collective quantum states, influenced by the surrounding neuron. These states would eventually undergo the objective reduction described earlier. The proposed information processing would connect activity inside neurons with their electrical signaling. <a href="https://doi.org/10.3389/fnmol.2022.869935">Hameroff develops this argument in his work on the neuronal cytoskeleton</a>.</p><p>His work in anesthesiology provided another reason to investigate. General anesthesia offers a way to study changes in consciousness by altering brain function. If microtubules participate in conscious experience, then substances that interact with them might influence how an animal responds to an anesthetic.</p><p>A 2024 study explored this possibility. Researchers compared eight male rats’ responses to the anesthetic isoflurane before and after treatment with <em>epothilone B</em>, a drug that stabilizes microtubules. Following treatment, the rats took an average of 69 seconds longer to lose their righting reflex — the ability to turn themselves upright when placed on their backs. The researchers used this reflex as a behavioral proxy for unconsciousness. The findings were published in <a href="https://doi.org/10.1523/ENEURO.0291-24.2024"><em>eNeuro</em></a>.</p><p>This result gives researchers a reason to investigate microtubules’ role in anesthetic action. Establishing Orch OR would require further evidence connecting that role to its specific quantum mechanism.</p><p>That brings us to a major physical challenge: whether the quantum states required by the proposal could persist long enough inside a living brain.</p><h3>The Challenge of Quantum Coherence</h3><p>The brain is warm, chemically active, and constantly interacting with its surroundings. For Orch OR, this creates a difficult question: can the quantum states it requires survive long enough to play their proposed role?</p><p>The concern centers on <em>decoherence</em>. Quantum interference depends on relationships between the components of a superposition. Interactions with the environment can make that interference effectively inaccessible within the system being studied. Decoherence describes this loss of accessible interference. Penrose’s objective reduction proposes a further physical event that selects a definite outcome. <a href="https://arxiv.org/abs/quant-ph/0312059">Physicist Maximilian Schlosshauer explains this distinction in his review of decoherence and the measurement problem</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f-ZAEfsezuEBtXqM9cDdrg.png" /><figcaption>Image generated by ChatGPT to illustrade the concept.</figcaption></figure><p>In a paper published in 2000, physicist Max Tegmark calculated that coherence in the microtubule model he examined would disappear in roughly 10⁻¹³ seconds. That is vastly shorter than the millisecond timescales associated with much neuronal activity. His calculations posed a serious challenge to proposals connecting quantum coherence with consciousness. <a href="https://doi.org/10.1103/PhysRevE.61.4194">Tegmark presented the analysis in <em>Physical Review E</em></a>.</p><p>Scott Hagan, Stuart Hameroff, and Jack Tuszyński challenged the assumptions behind that calculation. They argued that Tegmark had modeled a different physical superposition from the one proposed in Orch OR. Their revised calculations produced longer coherence times, and they suggested biological mechanisms that might extend them further. These were theoretical estimates whose relevance depends on the physical states and conditions actually present in neurons. <a href="https://arxiv.org/abs/quant-ph/0005025">Their response details the disagreement</a>.</p><p>Experiments offer another way to investigate these questions. A study published in 2023 reported that electronic excitation energy could migrate through laboratory preparations of microtubules, and that two anesthetics reduced this migration. This provides a measurable phenomenon to investigate, while leaving open its connection to the specific coherent states required by Orch OR. <a href="https://doi.org/10.1021/acscentsci.2c01114">The research appeared in <em>ACS Central Science</em></a>.</p><p>For Orch OR, the experimental task is therefore quite specific: identify the relevant quantum states in living neurons, establish how long they persist, and show how they contribute to conscious experience. Its proposed gravity-related collapse would also need evidence.</p><p>Each connection — from molecular activity to quantum coherence, and from quantum coherence to awareness — has to be tested.</p><h3>From Quantum Events to Conscious Experience</h3><p>Imagine listening to a favorite song. Your brain processes its sounds, recognizes patterns, and may retrieve memories associated with it. There is also the experience itself: how the music feels to you.</p><p>Philosopher David Chalmers called the challenge of explaining why physical processing is accompanied by subjective experience the <em>hard problem of consciousness</em>. Explaining how a system recognizes a melody addresses a function; explaining why hearing it feels like anything addresses experience. He developed this distinction in his 1995 paper, “<a href="https://doi.org/10.1093/acprof:oso/9780195311105.003.0001">Facing Up to the Problem of Consciousness.</a>”</p><p>Orch OR addresses this question by proposing that objective reduction events constitute moments of experience, with biological orchestration shaping those moments into organized consciousness. This proposed connection between physics and experience is a central assumption of the theory. Demonstrating quantum activity in microtubules would establish only part of that argument. <a href="https://doi.org/10.1016/j.plrev.2013.08.002">Penrose and Hameroff describe the connection in their review</a>.</p><p>That suggests a demanding standard for evaluating the proposal. Researchers would need predictions linking its specific quantum mechanism to measurable features of consciousness. Those predictions should help distinguish Orch OR from explanations based on other cellular processes or neuronal networks. An experiment would also need clear criteria for which results would challenge the proposal.</p><p>Consciousness research has begun using this approach to compare competing explanations. In a study published in 2025, researchers tested predictions agreed upon in advance by proponents of <em>global neuronal workspace theory</em> and <em>integrated information theory</em>. The findings supported some predictions while challenging important claims from both theories. <a href="https://doi.org/10.1038/s41586-025-08888-1">The collaboration published its results in <em>Nature</em></a>.</p><p>For Orch OR, a similarly useful test would identify an observation that its proposed mechanism predicts differently from competing accounts. The outcome could strengthen the hypothesis, expose a weakness, or require a revision. Each possibility would help clarify whether quantum physics contributes to consciousness in the particular way Penrose and Hameroff envision.</p><h3>Returning to the Central Question</h3><p>I began with a broad question: <strong>could quantum physics help explain consciousness?</strong> Exploring Orch OR has turned that question into several more precise ones. <strong>Which quantum processes could matter? Could they persist inside living neurons? What role would gravity play? And how would any of those events connect to conscious experience?</strong></p><p>Penrose and Hameroff offer a proposal that brings these questions together. Its appeal is easy to understand: it connects the biology inside our brains with fundamental questions about physical reality. Establishing that connection, however, requires evidence for each step. The studies discussed here leave substantial parts of the proposed mechanism unresolved.</p><p>What interests me most is the opportunity to follow an idea across disciplines while keeping track of where observation ends and hypothesis begins. Microtubules have measurable properties. Anesthetics produce observable changes. Quantum coherence and gravitational collapse make physical claims that researchers can investigate. Connecting those findings to experience is the demanding task at the center of Orch OR.</p><h3>What Comes Next: The Open Questions</h3><p>These are the developments I would watch most closely:</p><p><strong>- Measuring the relevant quantum states in living neurons.</strong> Which states does Orch OR require, how long do they persist, and how could researchers establish their role during conscious processing?</p><p>- <strong>Clarifying the anesthesia connection.</strong> A <a href="https://doi.org/10.1016/j.neuropharm.2026.110834">2026 mouse study</a> extended the microtubule-related anesthesia findings previously reported in rats. The question I would follow is which molecular mechanism explains the altered anesthetic response, and whether that mechanism specifically requires the quantum processes proposed by Orch OR.</p><p><strong>- Testing the proposed role of gravity.</strong> Objective reduction needs a precise physical model that agrees with experimental constraints. <a href="https://doi.org/10.1038/s41567-020-1008-4">Tests of gravity-related collapse models</a> already constrain particular versions, making the details of the proposed mechanism essential.</p><p><strong>- Connecting physical events to particular experiences.</strong> A stronger account would explain how its proposed processes relate to the contents and timing of experience, with predictions that distinguish it from competing explanations.</p><p><strong>- Building confidence through independent tests.</strong> I would look for reproducible findings across laboratories, clearly stated predictions, and agreement in advance about which outcomes would challenge the theory.</p><p>Following the evidence will determine how much of Orch OR holds.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93dba7dc8369" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modern Linux Drivers 3: Adding ioctl (and a std::expected) to Char Device]]></title>
            <link>https://erickof.medium.com/modern-linux-drivers-3-adding-ioctl-and-a-std-expected-to-char-device-2883e258c892?source=rss-1615d8d84c36------2</link>
            <guid isPermaLink="false">https://medium.com/p/2883e258c892</guid>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[driver]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Erick Andrés Obregón Fonseca]]></dc:creator>
            <pubDate>Mon, 27 Jul 2026 08:24:13 GMT</pubDate>
            <atom:updated>2026-07-27T08:24:31.863Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uAYFIlwQGl2D6yogesyR4A.png" /></figure><p>This is the third part of my previous posts about coding a Linux Driver from scratch. I strongly recommend you read <a href="https://erickof.medium.com/modern-linux-drivers-from-scratch-using-c-ed8ea4183496">Part 1</a> and <a href="https://erickof.medium.com/modern-linux-drivers-2-communicating-with-user-space-char-device-using-c-classes-1f1629a24023">Part 2</a> first.</p><p>So far, our <em>CharacterDevice</em> class can <em>read()</em> and <em>write()</em> a stream of bytes, and it manages its own registration lifetime through RAII. That covers the “data path” — but every real device eventually needs a way to say something that is not data. Today we give our driver such functionality, using <em>ioctl</em>, and we will use the opportunity to clean up our error handling with <em>std::expected</em>.</p><h3>Why read() and write() Are not Enough</h3><p>A byte stream is great for data, but terrible for commands. Imagine trying to tell the driver “switch to mode 2” by writing a byte sequence and hoping nobody ever wants to write that exact sequence as data. It works, but it is fragile, and it pollutes a channel that should carry payload.</p><p>This is exactly the gap <em>ioctl </em>(Input/Output Control) was built to fill: a side channel for commands and small structured exchanges that live outside the normal read/write path.</p><h3>Extending the Interface</h3><p>In the previous post, our <em>CharacterDevice </em>interface exposed <em>on_open</em>, <em>on_release</em>, <em>on_read</em>, and <em>on_write</em>, each backed by a static trampoline. Adding <em>ioctl </em>support means doing the same thing one more time:</p><pre>class CharacterDevice<br>{<br>public:<br>  virtual ~CharacterDevice() = default;<br><br>  // The interface that subclasses will implement<br>  virtual int on_open(struct inode *inode, struct file *file) = 0;<br>  virtual int on_release(struct inode *inode, struct file *file) = 0;<br>  virtual ssize_t on_read(struct file *file, char __user *buf, size_t len, loff_t *off) = 0;<br>  virtual ssize_t on_write(struct file *file, const char __user *buf, size_t len, loff_t *off) = 0;<br>  virtual long on_ioctl(struct file *file, unsigned int cmd, unsigned long arg) = 0;<br><br>  // The static methods<br>  static int fops_open(struct inode *inode, struct file *file);<br>  static int fops_release(struct inode *inode, struct file *file);<br>  static ssize_t fops_read(struct file *file, char __user *buf, size_t len, loff_t *off);<br>  static ssize_t fops_write(struct file *file, const char __user *buf, size_t len, loff_t *off);<br>  static long fops_ioctl(struct file *file, unsigned int cmd, unsigned long arg);<br>};</pre><p>The trampoline itself is nothing new — same <em>private_data </em>trick as before:</p><pre>long CharacterDevice::fops_ioctl(struct file *file, unsigned int cmd, unsigned long arg)<br>{<br>    auto* self = static_cast&lt;CharacterDevice*&gt;(file-&gt;private_data);<br>    return self-&gt;on_ioctl(file, cmd, arg);<br>}</pre><h3>Defining Our Commands</h3><p>Linux ioctl numbers are not arbitrary integers. They are built with the <em>_IO</em>, <em>_IOR</em>, <em>_IOW</em>, and <em>_IOWR</em> macros, which encode a “magic” character, a sequence number, and (for <em>_IOR</em>/<em>_IOW</em>/<em>_IOWR</em>) the size of the data being transferred. This encoding lets the kernel catch a driver being called with the wrong argument type or size, rather than silently misinterpreting memory.</p><pre>#define EDRV_MAGIC &#39;e&#39;<br><br>#define EDRV_RESET      _IO(EDRV_MAGIC, 1)<br>#define EDRV_GET_STATUS _IOR(EDRV_MAGIC, 2, int)<br>#define EDRV_SET_MODE   _IOW(EDRV_MAGIC, 3, int)</pre><h3>A Cleaner Internal Error Type with std::expected</h3><p>A typical <em>ioctl </em>handler ends up as a <em>switch </em>statement full of <em>copy_to_user</em>/<em>copy_from_user</em> calls, each with its own <em>-EFAULT</em>/<em>-EINVAL</em>/<em>-EAGAIN</em> return dotted through the logic. It works, but it reads like a maze of early returns, and it is easy to lose track of the path.</p><p><em>std::expected&lt;T, E&gt;</em> (C++23) gives us a value-or-error type we can build the actual decision logic around, and only translate to a raw kernel <em>errno </em>at the very boundary:</p><pre>enum class DriverError<br>{<br>    InvalidArgument,<br>    NotReady,<br>    HardwareFault,<br>};<br><br>constexpr int to_errno(DriverError err)<br>{<br>    switch (err)<br>    {<br>        case DriverError::InvalidArgument: return -EINVAL;<br>        case DriverError::NotReady:        return -EAGAIN;<br>        case DriverError::HardwareFault:   return -EIO;<br>    }<br><br>    return -EINVAL;<br>}<br><br>std::expected&lt;int, DriverError&gt; EchoDriver::handle_ioctl(unsigned int cmd, unsigned long arg)<br>{<br>    switch (cmd)<br>    {<br>        case EDRV_RESET:<br>        {<br>            mode = 0;<br>            msg_size = 0;<br>            return 0;<br>        }<br>        case EDRV_GET_STATUS:<br>        {<br>            int status = ready ? 1 : 0;<br>            if (copy_to_user(reinterpret_cast&lt;int __user *&gt;(arg), &amp;status, sizeof(status)))<br>                return std::unexpected(DriverError::HardwareFault);<br>            return 0;<br>        }<br>        case EDRV_SET_MODE:<br>        {<br>            int requested {};<br><br>            if (copy_from_user(&amp;requested, reinterpret_cast&lt;int __user *&gt;(arg), sizeof(requested)))<br>                return std::unexpected(DriverError::HardwareFault);<br><br>            if (requested &lt; 0 || requested &gt; 2)<br>                return std::unexpected(DriverError::InvalidArgument);<br><br>            mode = requested;<br>            return 0;<br>        }<br><br>        default:<br>            return std::unexpected(DriverError::InvalidArgument);<br>    }<br>}</pre><p>The kernel-facing <em>on_ioctl </em>override becomes a two-line adapter. Same “Kernel Interface vs. Logic Interface” split we used for <em>read</em>/<em>write </em>in Part 2, now extended to error handling:</p><pre>long EchoDriver::on_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)<br>{<br>    auto result = handle_ioctl(cmd, arg);<br>    if (!result.has_value()) return to_errno(result.error());<br>    return *result;<br>}</pre><p><strong>A note on using <em>std::expected</em> in kernel space:</strong> kernel modules are built with <em>-fno-exceptions -fno-rtti</em>, so we deliberately avoid <em>.value()</em> here. It throws <em>bad_expected_access</em> on an empty result, and exceptions are not available in this environment. Sticking to <em>has_value()</em>, <em>operator*</em>, and <em>error()</em> keeps us entirely inside the non-throwing subset of <em>std::expected</em>, which is what makes it usable here at all.</p><h3>Wiring It Into file_operations</h3><p>One more field in our <em>file_operations</em> struct, and the driver understands commands:</p><pre>static const struct file_operations my_fops = {<br>    .owner = THIS_MODULE,<br>    .read = CharacterDevice::fops_read,<br>    .write = CharacterDevice::fops_write,<br>    .open = CharacterDevice::fops_open,<br>    .release = CharacterDevice::fops_release,<br>    .unlocked_ioctl = CharacterDevice::fops_ioctl,<br>};</pre><h3>Calling It from User Space</h3><pre>#include &lt;sys/ioctl.h&gt;<br>#include &lt;fcntl.h&gt;<br>#include &lt;unistd.h&gt;<br>#include &lt;cerrno&gt;<br>#include &lt;cstring&gt;<br>#include &lt;print&gt;<br><br>#define EDRV_MAGIC &#39;e&#39;<br>#define EDRV_RESET      _IO(EDRV_MAGIC, 1)<br>#define EDRV_GET_STATUS _IOR(EDRV_MAGIC, 2, int)<br>#define EDRV_SET_MODE   _IOW(EDRV_MAGIC, 3, int)<br><br>int main()<br>{<br>    int fd = open(&quot;/dev/echo_dev&quot;, O_RDWR);<br>    if (fd &lt; 0)<br>    {<br>        std::println(stderr, &quot;Failed to open device. Try sudo.&quot;);<br>        return 1;<br>    }<br><br>    int mode = 2;<br>    if (ioctl(fd, EDRV_SET_MODE, &amp;mode) &lt; 0)<br>    {<br>        std::println(stderr, &quot;SET_MODE failed: {}&quot;, std::strerror(errno));<br>        close(fd);<br>        return 1;<br>    }<br><br>    int status = 0;<br>    if (ioctl(fd, EDRV_GET_STATUS, &amp;status) &lt; 0)<br>    {<br>        std::println(stderr, &quot;GET_STATUS failed: {}&quot;, std::strerror(errno));<br>        close(fd);<br>        return 1;<br>    }<br><br>    std::println(&quot;Driver status: {}&quot;, status);<br><br>    close(fd);<br>    return 0;<br>}</pre><p>Run it the same way as before:</p><pre>sudo insmod driver.ko<br>sudo chmod 666 /dev/echo_dev<br>g++ test_app.cpp -o test_app<br>./test_app</pre><h3>Conclusion</h3><p>Our driver can now do more than move bytes. It can be reset, queried, and reconfigured through a proper command channel, and the messy validation logic behind that channel lives in one clean, testable function instead of being smeared across a <em>switch </em>statement.</p><p>Please let me know what you would like to see next.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2883e258c892" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modern Linux Drivers 2: Communicating with User Space (Char Device) using C++ Classes]]></title>
            <link>https://erickof.medium.com/modern-linux-drivers-2-communicating-with-user-space-char-device-using-c-classes-1f1629a24023?source=rss-1615d8d84c36------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f1629a24023</guid>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[driver]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[Erick Andrés Obregón Fonseca]]></dc:creator>
            <pubDate>Sat, 11 Apr 2026 21:02:09 GMT</pubDate>
            <atom:updated>2026-07-27T08:13:30.791Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GB8uju3Ndnl1epYAdcYwcg.png" /></figure><p>This is the second part of my previous post about how to code a Linux Driver from scratch. I strongly recommend that you go over it first.</p><p><a href="https://erickof.medium.com/modern-linux-drivers-from-scratch-using-c-ed8ea4183496">Modern Linux Drivers 1: From Scratch Using C</a></p><h3>What’s a Character Device?</h3><p>Recalling the Linux philosophy, “everything is a file.” Whether we are talking to a hard drive, a keyboard, or a temperature sensor, the kernel exposes these hardware components to the user space as entries in the file system, typically located under <em>/dev</em>.</p><p>Among the different types of device drivers, the Character Device is perhaps the most common. Unlike block devices (like hard drives) that handle data in fixed-sized chunks and support random access, a character device handles data as a stream of bytes. It is like a serial port or a keyboard: we read or write data sequentially, character by character (or byte by byte).</p><p>When a user-space application wants to interact with the driver, it doesn’t call the kernel functions directly. Instead, it uses standard POSIX system calls. The path looks like this:</p><ol><li><strong>User Space:</strong> An application calls <em>open(/dev/my_device)</em>, <em>read()</em>, or <em>write()</em>.</li><li><strong>VFS (Virtual File System):</strong> The kernel looks at the file, identifies it as a character device, and finds which driver is responsible for it using its Major and Minor numbers (review this concept from the previous post).</li><li><strong>Kernel Space:</strong> The kernel forwards the request to the driver’s specific implementation of those operations.</li></ol><h3>Mapping C Structs to C++ Methods</h3><p>In traditional C kernel development, we would define a <em>struct file_operations</em> (as you probably remember from the previous post) containing raw function pointers. This structure is essentially a contract: it tells the kernel, “When a user calls <em>read()</em> on this file, execute this specific function.”</p><p>In this post, we are taking a different approach. Our goal is to encapsulate this behaviour within a C++ Class. By doing this, we can treat a character device as an object with its own state. Instead of managing global variables for the driver’s data, we can store them as private members of our class, ensuring that the interface between the user and the hardware is clean, safe, and modular. In standard C, this is straightforward. In Modern C++, however, we face a hurdle: The <em>this </em>pointer.</p><p>Kernel function pointers have a specific signature, such as:</p><pre>ssize_t *read(struct file *, char __user *, size_t, loff_t *)</pre><p>A C++ non-static member function has a hidden first argument: the pointer to the object instance (<em>this</em>). Because of this mismatch, we cannot simply plug a C++ method into a kernel struct.</p><p>To solve this, we use static methods as our new friends. These functions match the C signature perfectly, intercept the call, find the correct C++ object instance, and then delegate the work to a proper virtual (or CRTP) member function.</p><p>How does the static method know which instance of our class to use? The Linux Kernel provides a convenient hook in the struct file: the <em>void *private_data</em> field.</p><p>The workflow looks like this:</p><ol><li><strong>Open:</strong> When the user opens the device, our static <em>open </em>function is called. We find our C++ object and store it in <em>file-&gt;private_data</em>.</li><li><strong>Read/Write:</strong> When the user reads or writes, our static method retrieves the object from <em>private_data</em> and calls the instance method.</li></ol><p>To keep our code “Modern,” we define an interface that our driver must implement. This ensures that any character device we build follows the same predictable pattern:</p><pre>class CharacterDevice<br>{<br>public:<br>    virtual ~CharacterDevice() = default;<br><br>    // The interface that subclasses will implement<br>    virtual int on_open(struct inode *inode, struct file *file) = 0;<br>    virtual int on_release(struct inode *inode, struct file *file) = 0;<br>    virtual ssize_t on_read(struct file *file, char __user *buf, size_t len, loff_t *off) = 0;<br>    virtual ssize_t on_write(struct file *file, const char __user *buf, size_t len, loff_t *off) = 0;<br><br>    // The static methods<br>    static int fops_open(struct inode *inode, struct file *file);<br>    static int fops_release(struct inode *inode, struct file *file);<br>    static ssize_t fops_read(struct file *file, char __user *buf, size_t len, loff_t *off);<br>    static ssize_t fops_write(struct file *file, const char __user *buf, size_t len, loff_t *off);<br>};</pre><p>By decoupling the Kernel Interface (static) from the Logic Interface (virtual/member), we create a reusable boilerplate that allows us to write driver logic in pure C++ without worrying about the underlying C mechanics every time.</p><p>Something to take into consideration is that while <em>virtual </em>functions have a tiny overhead, in the context of <em>read/write</em> system calls (which are already expensive), the safety and organization they provide are usually well worth it.</p><h3>Implementation</h3><p>To make this work, we need to implement the static methods we defined in our interface. The most critical part is the <em>open </em>function, as it sets the stage for all subsequent operations.</p><p>When a user opens <em>/dev/our_device</em>, the kernel passes a <em>struct inode</em>. This structure contains a pointer to the <em>cdev </em>(character device) we registered. We can use the <em>container_of</em> macro to find the instance of our C++ class that contains that <em>cdev</em>.</p><pre>int CharacterDevice::fops_open(struct inode *inode, struct file *file)<br>{<br>    // 1. Get the pointer to the C++ instance using container_of<br>    auto* self = container_of(inode-&gt;i_cdev, CharacterDevice, cdev_member);<br>    <br>    // 2. Store it in private_data for future read/write calls<br>    file-&gt;private_data = self;<br>    <br>    // 3. Delegate to the instance method<br>    return self-&gt;on_open(inode, file);<br>}</pre><p>Once <em>private_data</em> is set, the read and write methods become much simpler. They no longer need to hunt for the instance, they just cast the pointer and go.</p><pre>ssize_t CharacterDevice::fops_read(struct file *file, char __user *buf, size_t len, loff_t *off)<br>{<br>    auto* self = static_cast&lt;CharacterDevice*&gt;(file-&gt;private_data);<br>    return self-&gt;on_read(file, buf, len, off);<br>}</pre><h3>Automatic Resource Management (RAII)</h3><p>In C, if we fail to unregister our device or forget to destroy the device class in the <em>exit </em>function, we will likely crash the kernel or leave ghost devices in <em>/sys/class</em>. By using C++, we can leverage the constructor and destructor to handle the heavy lifting. This follows the RAII (Resource Acquisition Is Initialization) pattern.</p><p><strong>The Registration Flow</strong></p><p>In our constructor (or an <em>init()</em> method), we should perform these four steps:</p><ol><li><strong>Allocate Region:</strong> <em>alloc_chrdev_region()</em> to get a major number.</li><li><strong>Initialize Cdev:</strong> <em>cdev_init()</em> and link it to our <em>file_operations</em> struct (which points to your static trampolines).</li><li><strong>Create Class:</strong> <em>class_create()</em> to group our devices in <em>/sys/class</em>.</li><li><strong>Create Device:</strong> <em>device_create()</em> to automatically create the entry in <em>/dev</em>.</li></ol><p>Inside our <em>.cpp</em> file, we will define the bridge that the kernel actually sees:</p><pre>static const struct file_operations my_fops = {<br>    .owner = THIS_MODULE,<br>    .read = CharacterDevice::fops_read,<br>    .write = CharacterDevice::fops_write,<br>    .open = CharacterDevice::fops_open,<br>    .release = CharacterDevice::fops_release,<br>};</pre><h3>Security: Talking to User Space</h3><p><strong>One final rule:</strong> Never trust User Space. We cannot simply use <em>memcpy</em> to move data from our driver to a user application. User-provided pointers can be malicious or point to unmapped memory, which would cause a kernel panic.</p><p>We must use the kernel’s safe API:</p><ol><li><strong><em>copy_to_user(dest, src, n)</em>:</strong> To send data to the app.</li><li><strong><em>copy_from_user(dest, src, n)</em>:</strong> To receive data from the app.</li></ol><p>In our C++ implementation, we can wrap these in a more “Modern” way, perhaps using <em>std::span</em> or a simple <em>template </em>to ensure we are not overstepping buffer boundaries.</p><h3>Putting All Together</h3><p>First, let’s start with the Kernel Space code. Here is the implementation:</p><pre>#include &lt;linux/module.h&gt;<br>#include &lt;linux/device.h&gt;<br>#include &lt;linux/cdev.h&gt;<br>#include &lt;linux/uaccess.h&gt; // copy_to_user / copy_from_user<br>#include &lt;linux/slab.h&gt;<br><br>class EchoDriver<br>{<br>private:<br>    dev_t dev_num {0};<br>    struct class* dev_class = {nullptr};<br>    struct cdev my_cdev {};<br>    static constexpr size_t MaxBufferSize {256};<br>    char message[MaxBufferSize] = {0};<br>    size_t msg_size {0};<br><br>public:// Delete copy and move to ensure RAII integrity<br>    EchoDriver(const EchoDriver&amp;) = delete;<br>    EchoDriver&amp; operator=(const EchoDriver&amp;) = delete;<br><br>    EchoDriver()<br>    {<br>        // 1. Allocate major/minor numbers<br>        if (alloc_chrdev_region(&amp;dev_num, 0, 1, &quot;echo_driver&quot;) &lt; 0) return;<br><br>        // 2. Create the /sys/class entry<br>        dev_class = class_create(&quot;echo_class&quot;);<br>        if (IS_ERR(dev_class)) unregister_chrdev_region(dev_num, 1);<br><br>        // 3. Initialize cdev and bind to fops<br>        cdev_init(&amp;my_cdev, &amp;fops);<br>        if (cdev_add(&amp;my_cdev, dev_num, 1) &lt; 0) class_destroy(dev_class);<br><br>        // 4. Create the /dev/echo_dev node<br>        if (IS_ERR(device_create(dev_class, nullptr, dev_num, nullptr, &quot;echo_dev&quot;))) cdev_del(&amp;my_cdev);<br>        <br>        pr_info(&quot;Echo Driver: Loaded with Major %d\n&quot;, major);<br>    }<br><br>    ~EchoDriver()<br>    {<br>        device_destroy(dev_class, dev_num);<br>        class_destroy(dev_class);<br>        cdev_del(&amp;my_cdev);<br>        unregister_chrdev_region(dev_num, 1);<br>        pr_info(&quot;Echo Driver: Resources released\n&quot;);<br>    }<br><br>    // Logic Implementation<br>    ssize_t read(struct file* filp, char __user* buf, size_t len, loff_t* off)<br>    {<br>        if (*off &gt;= static_cast&lt;loff_t&gt;(msg_size)) return 0;<br><br>        size_t available = msg_size - *off;<br>        size_t to_copy = (len &lt; available) ? len : available;<br><br>        if (copy_to_user(buf, message + *off, to_copy)) return -EFAULT;<br>        <br>        *off += to_copy;<br>        return static_cast&lt;ssize_t&gt;(to_copy);<br>    }<br><br>    ssize_t write(struct file* filp, const char __user* buf, size_t len, loff_t* off)<br>    {<br>        msg_size = (len &lt; MaxBufferSize) ? len : MaxBufferSize;<br>        if (copy_from_user(message, buf, msg_size)) return -EFAULT;<br>        return static_cast&lt;ssize_t&gt;(msg_size);<br>    }<br><br>    // Static methods<br>    static ssize_t dev_read(struct file* filp, char __user* buf, size_t len, loff_t* off)<br>    {<br>        auto* self = container_of(filp-&gt;f_inode-&gt;i_cdev, EchoDriver, my_cdev);<br>        return self-&gt;read(filp, buf, len, off);<br>    }<br><br>    static ssize_t dev_write(struct file* filp, const char __user* buf, size_t len, loff_t* off)<br>    {<br>        auto* self = container_of(filp-&gt;f_inode-&gt;i_cdev, EchoDriver, my_cdev);<br>        return self-&gt;write(filp, buf, len, off);<br>    }<br><br>    static inline struct file_operations fops = {<br>        .owner = THIS_MODULE,<br>        .read = EchoDriver::dev_read,<br>        .write = EchoDriver::dev_write,<br>    };<br>};<br><br>// Global instance<br>static EchoDriver* g_driver {nullptr};<br><br>extern &quot;C&quot; {<br>    int init_module(void)<br>    {<br>        g_instance = new (kmalloc(sizeof(EchoDriver), GFP_KERNEL)) EchoDriver();<br>        return g_instance ? 0 : -ENOMEM;<br>    }<br><br>    void cleanup_module(void)<br>    {<br>        if (g_instance) {<br>            g_instance-&gt;~EchoDriver();<br>            kfree(g_instance);<br>        }<br>    }<br>}</pre><p>Now we can code a C++ application that interacts with our driver as if it were a plain text file.</p><pre>#include &lt;print&gt;<br>#include &lt;expected&gt;<br>#include &lt;fstream&gt;<br>#include &lt;string&gt;<br>#include &lt;filesystem&gt;<br>#include &lt;string_view&gt;<br><br>auto verify_device(const std::filesystem::path&amp; dev_path) -&gt; std::expected&lt;void, std::string&gt;<br>{<br>    if (!std::filesystem::exists(dev_path))<br>    {<br>        return std::unexpected(&quot;Device &quot; + dev_path.string() + &quot; does not exist. Did you load the module?&quot;);<br>    }<br>    return {};<br>}<br><br>int main()<br>{<br>    const std::filesystem::path dev_path {&quot;/dev/echo_dev&quot;};<br>    constexpr std::string_view my_msg {&quot;Hello from User Space!&quot;};<br><br>    // 1. Check if device is available<br>    auto result = verify_device(dev_path);<br>    if (!result)<br>    {<br>        std::println(stderr, &quot;Error: {}&quot;, result.error());<br>        return 1;<br>    }<br><br>    // 2. Write to the driver<br>    {<br>        std::ofstream writer(dev_path);<br>        if (!writer)<br>        {<br>            std::println(stderr, &quot;Failed to open device for writing. Try sudo.&quot;);<br>            return 1;<br>        }<br>        writer &lt;&lt; my_msg;<br>        std::println(&quot;Sent: {}&quot;, my_msg);<br>    } // writer closes automatically here (RAII)<br><br>    // 3. Read back from the driver<br>    {<br>        std::ifstream reader(dev_path);<br>        if (std::string response; std::getline(reader, response))<br>        {<br>            std::println(&quot;Received: {}&quot;, response);<br>        }<br>        else<br>        {<br>            std::println(stderr, &quot;Failed to read from device.&quot;);<br>            return 1;<br>        }<br>    }<br><br>    return 0;<br>}</pre><p>With that done, we can now see our work in action, let’s run the following steps:</p><ol><li><strong>Compile the Kernel Module:</strong> Use our Makefile (from Part 1) to generate <em>driver.ko</em>.</li></ol><p><strong>2. Load the Driver:</strong></p><pre>sudo insmod driver.ko</pre><p><strong>3. Check Permissions:</strong> By default, <em>/dev/echo_dev</em> belongs to root. Change it so our app can access it:</p><pre>sudo chmod 666 /dev/echo_dev</pre><p><strong>4. Compile the App:</strong></p><pre>g++ test_app.cpp -o test_app</pre><p><strong>5. Run:</strong></p><pre>./test_app</pre><h3>Conclusion</h3><p>We have successfully bridged the gap between a high-level C++ application and a low-level kernel module. By using Character Devices, we’ve transformed our driver from a simple “Hello World” into a functional example.</p><p>Please let me know what you would like to see next.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f1629a24023" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[C++23 Series: 1. Enter… “std::println”]]></title>
            <link>https://erickof.medium.com/c-23-series-1-enter-std-println-6947917c1ba3?source=rss-1615d8d84c36------2</link>
            <guid isPermaLink="false">https://medium.com/p/6947917c1ba3</guid>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Erick Andrés Obregón Fonseca]]></dc:creator>
            <pubDate>Mon, 19 Jan 2026 06:02:47 GMT</pubDate>
            <atom:updated>2026-01-19T06:02:47.293Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Every programmer remembers their first Hello World, but in C++, that simple line of code has undergone a massive transformation. What started as a legacy inherited from C has evolved through the complex shovels of iostreams and the formatting revolution of C++20, culminating in the modern elegance of C++23. Let’s look at how we got here—and why you should stop using std::cout and std::endl forever.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*TRvaVa6HiOZwQpmT.png" /></figure><h3>The C Legacy</h3><p>In the beginning, there was printf. Inherited directly from C, this function was the gold standard for output for decades. Even after C++ introduced its own stream-based system, many veteran developers refused to let it go.</p><p>The core of printf is the format string. Instead of breaking the output into pieces, you provide a template with placeholders (format specifiers) and then pass the data as subsequent arguments.</p><pre>#include &lt;cstdio&gt;<br><br>int main()<br>{<br>  const char* user = &quot;Dev&quot;;<br>  int attempts = 3;<br>  float success_rate = 95.5;<br><br>  printf(&quot;User %s failed %d times. Success rate: %.1f%%\n&quot;,<br>          user, attempts, success_rate);<br>}</pre><p>Despite being “old,” printf has several objective advantages that kept it relevant:</p><ul><li><strong>Brevity:</strong> It is much more compact than the shovels of std::cout. Compare printf(&quot;%d&quot;, x) to std::cout &lt;&lt; x.</li><li><strong>Performance:</strong> printf is generally faster than std::cout because it does not have the overhead of the C++ object-oriented stream synchronization and complex locale handling.</li><li><strong>Formatting Control:</strong> Specifying things like “pad with zeros to 5 places” (%05d) or &quot;show two decimal points&quot; (%.2f) is extremely easy to write and read.</li></ul><p>The reason C++ eventually moved away from printf is not about style—it is about safety.</p><h4>1. No Type Safety</h4><p>printf is a variadic function. It has no idea what you are actually passing to it — it blindly trusts the format string. If you provide %s (a string) but accidentally pass an int, the program will attempt to read memory at that integer&#39;s address, which will result into alikely segmentation fault or a crash.</p><h4>2. Security Vulnerabilities</h4><p>Because printf parses the format string at runtime, it is susceptible to format string attacks. If an attacker can provide part of the format string, they can potentially leak memory contents or even overwrite parts of the stack.</p><h4>3. Lack of Extensibility</h4><p>printf only understands &quot;primitive&quot; types (int, char, float). If you create a struct Robot or a class Engine, you cannot teach printf how to handle it. You are forced to manually extract the members: printf(&quot;%s&quot;, myRobot.getName()).</p><h3>The Object-Oriented Shift</h3><p>With the release of C++98, the language sought to break away from the dangers of C. The result was iostreams<em> </em>— a system built on the core principles of C++: OOP and operator overloading. While printf was a function, std::cout is an object. This represented a massive shift in how developers thought about data output.</p><p>The core idea was to treat the console not as a destination for a formatted template, but as a continuous sink where data could be poured. This is why we use the insertion operator (&lt;&lt;), which looks like an arrow pointing toward the output.</p><pre>#include &lt;iostream&gt;<br><br>int main()<br>{<br>    int score = 100;<br>    // Data &quot;flows&quot; from right to left into the cout object<br>    std::cout &lt;&lt; &quot;Your score is: &quot; &lt;&lt; score &lt;&lt; &quot;\n&quot;;<br>}</pre><p>Unlike printf, std::cout is aware of the data types it receives. Because the &lt;&lt; operator is overloaded for every primitive type, the compiler knows exactly which function to call. You can not accidentally pass a string to an integer placeholder because there are no placeholders.</p><p>Extensibility was the biggest win for C++. You could now teach std::cout how to handle your own custom classes. By overloading the operator&lt;&lt; globally, your custom objects became &quot;first-class citizens&quot; in the iostream world.</p><pre>struct Point { int x, y; };<br><br>// Teach C++ how to print a Point<br>std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const Point&amp; p)<br>{<br>    return os &lt;&lt; &quot;(&quot; &lt;&lt; p.x &lt;&lt; &quot;, &quot; &lt;&lt; p.y &lt;&lt; &quot;)&quot;;<br>}<br><br>Point pt = {10, 20};<br>// Outputs: (10, 20)<br>std::cout &lt;&lt; pt;</pre><p>Despite the safety, std::cout became one of the most criticized parts of the C++ standard library for two main reasons:</p><h4>1. State-Based Formatting</h4><p>If you want to print a number in hexadecimal or limit decimal places, you use manipulators. The problem? These manipulators change the state of the std::cout object globally until you manually change them back.</p><pre>#include &lt;iomanip&gt;<br><br>std::cout &lt;&lt; std::hex &lt;&lt; 255; // prints ff<br>std::cout &lt;&lt; 10;              // prints a (I wanted 10!)</pre><p>This stickiness leads to bugs where one part of a program accidentally breaks the formatting for the rest of the application.</p><h4>2. The Verbosity Explosion</h4><p>Formatting code became notoriously difficult to read. What was a single line in printf often turned into a &quot;train wreck&quot; of chevrons and manipulators.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*12FfsuyPypQpE_npSGI_JQ.png" /></figure><h3>Modern C++: The <em>fmt </em>Influence (C++20)</h3><p>By the time C++20 arrived, the community had reached a consensus: printf was too dangerous, but std::cout was too annoying<strong>.</strong> Developers were congregating at a third-party library called {fmt}. It was so successful that the C++ Standards Committee decided to bring its core philosophy into the official language. This era is defined by the return of the format string, but reimagined for a modern, safe world.</p><p>C++20 introduced the &lt;format&gt; header. It aimed to provide the readability of C’s printf with the type safety and extensibility of C++’s std::cout. Instead of the cryptic %d or %s, C++20 adopted the Python-style curly brace {} syntax.</p><pre>#include &lt;format&gt;<br>#include &lt;string&gt;<br>#include &lt;iostream&gt;<br><br>int main()<br>{<br>    std::string name = &quot;Modern C++&quot;;<br>    int version = 20;<br><br>    // The result is a std::string<br>    std::string message = std::format(&quot;Hello from {} {}!&quot;, name, version);<br>    std::cout &lt;&lt; message &lt;&lt; &quot;\n&quot;;<br>}</pre><p>Unlike printf, which waits until your program is running to fail, std::format allows the compiler to inspect your format string. If you try to format a complex object that does not support it, the code won’t compile.</p><p>Formatting is now contained within the braces. It uses a concise mini-language:</p><ul><li>{:x} : Hexadecimal.</li><li>{:05} : Pad with zeros to 5 places.</li><li>{:.2f} : Two decimal points.</li></ul><pre>// Much cleaner than std::setw and std::setfill<br>std::cout &lt;&lt; std::format(&quot;Hex: {:x}, Padded: {:05}\n&quot;, 255, 42);</pre><p>std::format was designed from the ground up to be fast. It avoids the heavy overhead of iostreams’ virtual function calls and locale-handling bottlenecks. In many benchmarks, it rivals or even beats printf.</p><p>Even though C++20 gave us a world-class formatting engine, it forgot one thing: a way to actually print<strong>. </strong>In C++20, std::format only creates a string. To see it on the screen, you still had to pass that string to std::cout or printf.</p><pre>// The C++20 &quot;Double Work&quot;<br>std::cout &lt;&lt; std::format(&quot;The answer is {}\n&quot;, 42);</pre><p>This felt like an awkward half-step. You were using the modern formatting engine, but still stuck in the old, slow iostream pipe. This inefficiency — allocating a temporary string just to print it — was the final hurdle for the committee to clear.</p><h3>The Modern Standard: std::print (C++23)</h3><p>C++23 is where the journey finally reaches its destination. The community realized that while std::format was a masterpiece of engineering, requiring developers to use std::cout to actually see the text was like buying a Ferrari engine but putting it inside a horse-drawn carriage.</p><p>The &lt;print&gt; header was introduced to provide a direct, high-performance path from your data to the console. This came with two primary functions:</p><ol><li>std::print: Formats and prints text exactly as specified.</li><li>std::println: Formats, prints, and automatically appends a newline (\n). This finally kills the std::endl vs \n debate for good.</li></ol><pre>#include &lt;print&gt;<br><br>int main()<br>{<br>    int year = 2023;<br>    // No more std::cout, no more &lt;&lt;, no more manual formatting steps<br>    std::println(&quot;C++{} is the new standard.&quot;, year);<br>}</pre><p>Why is this the “Gold Standard”?</p><h4>1. Zero-Allocation Printing</h4><p>In C++20, std::format created a temporary std::string object in memory before printing it. If you were printing millions of lines, those memory allocations slowed things down. std::print writes directly to the output stream’s buffer, bypassing the need to create a temporary string. It is the fastest way to print in C++.</p><h4>2. Native Unicode</h4><p>Historically, printing Unicode characters on Windows was a nightmare involving complex system calls. C++23 mandates that if the terminal supports it, std::print will output UTF-8 correctly across all platforms.</p><pre>#include &lt;print&gt;<br><br>int main()<br>{<br>    std::println(&quot;Hello, World! ✨&quot;);<br>}</pre><h4>3. Smaller Binary Sizes</h4><p>Because std::print does not rely on the massive, complex machinery of &lt;iostream&gt; (which often pulls in a lot of heavy code even for a “Hello World”), your compiled executable files can actually be smaller and more efficient.</p><h3>Conclusions</h3><p>The evolution of printing in C++ is a rare example of a language learning from its own history<strong>.</strong> We began with the simplicity of C’s format strings, deviated to the complex world of object-oriented streams and manipulators, and have finally returned to format strings — but this time, with the full power of the modern C++ type system behind them.</p><p>C++23 does not just provide a new way to see text on a screen — it represents a more mature, user-friendly era for the language. By moving away from the syntax of the 90s, C++ is proving that it can evolve to be as expressive and modern as languages like Rust or Python, without losing its high-performance edge.</p><p>The next time you start a project, leave &lt;&lt; in the past. It is time to embrace std::print.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6947917c1ba3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[C++23 Series: 0. Is C++ still worth it in 2026?]]></title>
            <link>https://erickof.medium.com/c-23-series-0-is-c-still-worth-it-in-2026-9aa08ed69b38?source=rss-1615d8d84c36------2</link>
            <guid isPermaLink="false">https://medium.com/p/9aa08ed69b38</guid>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Erick Andrés Obregón Fonseca]]></dc:creator>
            <pubDate>Thu, 15 Jan 2026 06:02:47 GMT</pubDate>
            <atom:updated>2026-01-15T06:02:47.800Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zr_xWePD8RNAf0h0iCXfoQ.png" /></figure><p>For the last few years, the tech industry has been flooded with “C++ is dead” headlines. Between the push of White House for memory-safe languages and the meteoric rise of Rust, it is easy to feel like C++ is slowly dying.</p><p>C++ isn’t just surviving… It is undergoing a massive architectural renaissance. With the full integration of C++23 — and the coming C++26 standard being baked—, we are seeing a language that finally prioritizes developer experience alongside its legendary performance. We have moved past the “C with Classes” era and even the “Modern C++11” era. We are now in the age of Scalable, Expressive C++.</p><p>The goal of this series isn’t to pretend C++ is perfect. It is to look at why it remains the backbone of our world — from the engines powering AAA games to the low-latency systems driving global finance — and how the C++23 standard fixes the pains that used to make development a chore.</p><h3>Memory Safety</h3><p>The criticism against C++ usually centres on one fact: it allows manual memory management. In the wrong hands, this leads to buffer overflows, use-after-free errors, and memory leaks. However, the narrative that C++ is inherently dangerous ignores the massive strides the language has made to protect developers from themselves.</p><p>The primary difference between C++ and Rust isn’t that C++ can’t be safe — it is that C++ gives you the keys to the engine. Rust enforces safety at the compiler level while Modern C++20/23 provides a safe subset. If you use smart pointers (<em>std::unique_ptr</em>, <em>std::shared_ptr</em>), containers (<em>std::vector</em>, <em>std::array</em>), and views (<em>std::span</em>, <em>std::string_view</em>), 90% of traditional memory bugs simply vanish.</p><p>C++23 introduced features that make “doing the right thing” the easiest path for the developer. The <em>std::expected</em> and <em>std::optional</em> extensions reduce the need for raw pointers to indicate <em>null</em> or <em>error</em> states. Instead of returning a pointer that might be null, you return a type that forces the caller to handle the error case. The <em>std::span</em> (introduced in C++20, refined in 23) allows us to pass arrays around without decaying them into dangerous raw pointers. It tracks the size automatically, preventing the classic out-of-bounds exploit.</p><p>The most exciting development is the progress of Bjarne Stroustrup’s profiles proposal. The goal is to allow developers to participate in specific safety guarantees at the compiler level. Imagine adding a single line to your build script: <em>set_cpp_profile(type_safety, bounds_safety, memory_safety)</em>. The compiler would then flag any legacy or unsafe code as a hard error.</p><h3>The Competitive Landscape: C++ vs. Rust vs. Carbon</h3><h4>Rust: The “Greenfield” Gold Standard</h4><p>Rust has officially moved from a trendy alternative to a corporate essential. If you are starting a new security-sensitive project from scratch — like a cloud-native microservice or a new kernel module — Rust is often the default choice.</p><p>Its Borrow Checker provides safety guarantees that C++ can only mimic through discipline. While Rust-to-C interoperability is solid, Rust-to-C++ interoperability remains a complex — often painful — bridge to cross for large, template-heavy codebases.</p><h4>Carbon: The “Successor” in the Wings</h4><p>Google’s Carbon language is the one to watch if you are working in a massive C++ shop. As of early 2026, Carbon is approaching its 0.1 Evaluation milestone.</p><p>Carbon isn’t trying to replace C++ overnight. It is designed to be to C++ what TypeScript is to JavaScript: a language that can live inside your existing build system, allowing you to migrate one file at a time while maintaining bi-directional compatibility.</p><p>Still experimental, but the “successor” model is gaining traction among engineers who find Rust’s migration path too steep.</p><h4>C++23/26: The “Ship of Theseus”</h4><p>C++ is essentially rebuilding itself from the inside out. With C++26 drafts finalizing this year, features like compile-time reflection and contracts are narrowing the gap between C++ and its modern rivals. Counterintuitively, competition has made C++ stronger. According to recent 2026 industry data, C++ is actually adding more total developers annually than some of its replacements have in their entire ecosystems.</p><p>While AI models are written in Python, the inference engines and kernels — the code that runs on the GPU/NPU — are almost exclusively C++. As AI demand scales, the demand for the engineers who can squeeze every ounce of performance out of the silicon — the C++ engineers — has hit a ten-year high.</p><h3>Conclusions</h3><p>While C++23 gave us the tools to write cleaner code today, C++26 is aiming to solve the meta-problems that have plagued the language for decades. For the first time, the language will have a standardized way to inspect its own types at compile time. This means that tedious, error-prone tasks like writing serialization code, ORM mapping, or even simple enum-to-string conversions can be automated entirely within the compiler.</p><p>After nearly two decades of debate, the contracts MVP allows developers to formally define preconditions, postconditions, and assertions. This doesn’t just help with debugging — it serves as a bridge for the memory safety conversation by allowing compilers and static analysis tools to prove that your code is behaving exactly as intended. When combined with the new Hardened Standard Library mode, C++26 allows you to simply recompile existing code to gain immediate, automated bounds-checking across your most-used containers.</p><p>Finally, we are seeing the industrialization of the C++ ecosystem. Tools like Visual Studio 2026 and the latest Clang/GCC releases are integrating AI-powered lifetime tracking and sophisticated modules support that finally makes “<em>import std;</em>” a production reality. The worth of C++ in 2026 isn’t just about speed anymore — it is about the fact that we are finally getting a language that is as expressive and safe as its modern rivals, without losing the zero-overhead soul that made it the foundation of the digital world in the first place.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9aa08ed69b38" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modern Linux Drivers 1: From Scratch Using C]]></title>
            <link>https://erickof.medium.com/modern-linux-drivers-from-scratch-using-c-ed8ea4183496?source=rss-1615d8d84c36------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed8ea4183496</guid>
            <category><![CDATA[driver]]></category>
            <category><![CDATA[c-language]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[Erick Andrés Obregón Fonseca]]></dc:creator>
            <pubDate>Sun, 11 Jan 2026 21:50:31 GMT</pubDate>
            <atom:updated>2026-04-11T21:04:18.977Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RODq9AV7CCIjWu-asF-XCg.png" /></figure><h3>Introduction</h3><p>In the world of embedded systems, whether you are building custom hardware on an FPGA or optimizing data transfer for a high-performance ARM or RISC-V processor, the bridge between hardware and software is the Linux Device Driver. Understanding how to write a Linux Device Driver is your gateway to the hardware.</p><p>A device driver is a specialized software module that implements standardized routines to control and access hardware modules. While the goal of a driver is to provide a uniform interface for users, the internal mechanics involve a sophisticated dance between two isolated execution environments: Kernel Space and User Space. Before we write code, we must understand the boundary we are crossing. Linux operates in two distinct modes:</p><ul><li><strong>Kernel Space:</strong> Here, the kernel manages the machine’s hardware directly, simply, and efficiently, providing a uniform API for developers. Any subroutine that is part of a driver or a kernel module is considered part of the kernel space. Interaction with hardware is done through direct reads and writes to reserved memory addresses or ports.</li><li><strong>User Space:</strong> This is where user-focused applications (shells, browsers, custom software) live. To prevent accidental or malicious hardware damage, these applications are strictly prohibited from interacting with hardware directly. Instead, they must rely on the kernel to act as a mediator, communicating through system calls (syscalls) or by interacting with files in the filesystem.</li></ul><h4>Everything is a File</h4><p>It is important to remember that the power of Linux development lies in the philosophy that “everything is a file”. From a user’s perspective, communicating with a sophisticated hardware module should be as simple as writing to or reading from a standard text file. In modern Linux systems, these hardware “files” are located in the /dev/ directory.</p><p>When a user application operates on a file — such as open(), read(), or write()—the kernel looks up the driver associated with that specific file. It then executes the corresponding kernel-level functions implemented by the driver developer. This bridge allows information to flow safely and predictably between the two spaces.</p><p>To link a file to a kernel module, two numbers are used: a Major and a Minor Number. Of these two, the Major Number is used by the kernel to link the file to the driver, and the Minor Number is used internally by the device.</p><h4>The Modern Standard: <em>miscdevice</em></h4><p>Historically, developers manually managed Major Numbers to link files to drivers. In modern system development, we use the miscdeviceAPI. This API automates much of the mainstream code — such as dynamic device node creation — allowing engineers to focus on the driver’s core logic rather than administrative kernel tasks.</p><h3>Load and Remove Driver From User Space</h3><p>In this first driver, I’m showing you how to load and remove a driver without functionality. For this, we are using a nothing.c file with the following content:</p><pre>#include &lt;linux/kernel.h&gt;<br><br>MODULE_LICENSE(&quot;Dual BSD/GPL&quot;);</pre><p>Before loading the driver, it must be compiled against the headers of the current Linux kernel. We use a standard Makefile that points to the build directory of the specific kernel version.</p><pre>obj-m := nothing.o</pre><p>Run the make command in the terminal. This will generate a .ko (kernel object) file, which is the binary format for the driver.</p><pre>make -C /usr/src/linux-headers-$(uname -r) M=$(pwd modules)</pre><p>In case you have any errors because it is not able to find a kernel, run this command:</p><pre>sudo apt-get install linux-headers-$(uname -r)</pre><p>Among other files, the compilation should have created a file called nothing.ko, which corresponds to the driver module.</p><p>In the user space, the module can be installed/loaded within the kernel with the command:</p><pre>sudo insmod nothing.ko</pre><p>To verify that the module has been loaded correctly, you can use the command:</p><pre>lsmod</pre><p>Finally, the module can be removed from the kernel using the command:</p><pre>sudo rmmod nothing</pre><h3>Load and Remove Driver From Kernel Space</h3><p>When you load a driver into the kernel, it must perform preliminary tasks such as reserving memory, setting up concurrency locks, or registering the device within the system. These tasks are implemented in space-specific functions: module_init() and module_exit(), which correspond to the user-space commands insmod and rmmod respectively.</p><p>The initialization function is the driver’s entry point. In modern development, this is where we register our device using the miscdevice structure, which automatically handles the creation of the /dev/ file entry. The exit function is responsible for undoing everything the initialization function did. This ensures that the system remains stable and that no “zombie” resources are left in memory.</p><p>The following code hello.c demonstrates the initialization and exit routines:</p><pre>#include &lt;linux/init.h&gt;<br>#include &lt;linux/module.h&gt;<br>#include &lt;linux/kernel.h&gt;<br>#include &lt;linux/miscdevice.h&gt;<br><br>MODULE_LICENSE(&quot;Dual BSD/GPL&quot;);<br><br>// The initialization function<br>static int __init hello_init(void)<br>{<br>  // pr_info works similarly to printf but at the kernel level<br>  pr_info(&quot;Driver: Hello world! Initializing module...\n&quot;);<br>    <br>  // In a full driver, this is where you would call <br>  // misc_register() to link the driver to /dev/<br>  return 0; // Success<br>}<br><br>// The exit function<br>static void __exit hello_exit(void)<br>{<br>  pr_info(&quot;Driver: Bye, cruel world. Cleaning up...\n&quot;);<br>    <br>  // In a full driver, this is where you would call <br>  // misc_deregister()<br>}<br><br>// Macros to register the entry and exit points with the kernel<br>module_init(hello_init);<br>module_exit(hello_exit);</pre><p>To compile this module, the Makefile must be modified to look like this:</p><pre>obj-m := hello.o</pre><p>The compilation command is the same as the previous section:</p><pre>make -C /usr/src/linux-headers-$(uname -r) M=$(pwd modules)</pre><p>When inserting (using insmod) the newly compiled hello.ko driver module, it must call the hello_init function, which will print a message to the system console, not the shell terminal. To view the system console, you can use the command:</p><pre>dmesg | tail</pre><p>Install/load the kernel with the command:</p><pre>sudo insmod hello.ko</pre><p>And remove it from the kernel using the command:</p><pre>sudo rmmod hello</pre><p>Verify that the corresponding messages are shown.</p><h3>Full Driver: A Virtual Character Device</h3><p>Finally, we transition from the basic “Nothing” or “Hello World” modules to a functional 64-bit Virtual Memory Driver. This driver allows a user-space application to store and retrieve an 8-byte value directly within the kernel’s memory. We also include a Mutex, which is mandatory in modern, multi-core environments to prevent “race conditions” where two programs try to access the data simultaneously.</p><h4>Linking the Device with its File</h4><p>As I mentioned previously, historically, developers had to manually manage Major Numbers to link a driver to a file. Since we now use the miscdevice<strong> </strong>API, this modern standard automatically assigns a major number and creates the device file as soon as the module is loaded, eliminating the need for manual commands like mknod.</p><h4>Defining the File Operations</h4><p>To bridge the gap between spaces, we define a file_operations structure. This structure tells the kernel which of our internal functions should execute when a user-space program tries to read or write to our device.</p><pre>static const struct file_operations memory_fops =<br>{<br>  .owner = THIS_MODULE,<br>  // Link to our read function<br>  .read  = memory_read,<br>  // Link to our write function<br>  .write = memory_write,<br>};</pre><p>This code will make more sense once we put it all together.</p><h4>Opening and Closing the Device</h4><p>Opening and closing a device in user space (using functions like fopen or fclose) triggers the open and release members of our driver. For this simple memory driver, these functions merely return success, but in hardware drivers, they are used to power on or reset physical modules.</p><h4>Reading from the Device</h4><p>When a user-space application reads from the device, the kernel calls memory_read. We use the standard copy_to_user function to safely transfer our 64-bit value from the kernel&#39;s protected memory into the user&#39;s application buffer.</p><pre><br>/**<br> * memory_read - Transfers data from Kernel to User Space<br> * Equivalent to &#39;fread&#39; or &#39;cat&#39; in User Space.<br> */<br>static ssize_t memory_read(struct file *filp, char __user *buf, size_t count, loff_t *f_pos)<br>{<br>  // End of File<br>  if (*f_pos &gt; 0) return 0;<br><br>  // Protect against concurrent access<br>  mutex_lock(&amp;memory_lock);<br><br>  // Standard safe transfer to User Space buffer<br>  if (copy_to_user(buf, &amp;memory_value, sizeof(u64)))<br>  {<br>    mutex_unlock(&amp;memory_lock);<br>    return -EFAULT;<br>  }<br><br>  mutex_unlock(&amp;memory_lock);<br>    <br>  *f_pos += sizeof(u64);<br><br>  // Return 8 bytes read<br>  return sizeof(u64);<br>}</pre><h4>Writing to the Device</h4><p>To store data, the user-space application writes to the device file. The kernel calls our memory_write function, where we use copy_from_user to receive the data and save it into our 64-bit kernel variable.</p><pre>/**<br> * memory_write - Transfers data from User to Kernel Space<br> * Equivalent to &#39;fwrite&#39; or &#39;echo&#39; in User Space.<br> */<br>static ssize_t memory_write(struct file *filp, const char __user *buf, size_t count, loff_t *f_pos)<br>{<br>  mutex_lock(&amp;memory_lock);<br><br>  // Standard safe transfer from User Space buffer<br>  if (copy_from_user(&amp;memory_value, buf, sizeof(u64)))<br>  {<br>    mutex_unlock(&amp;memory_lock);<br>    return -EFAULT;<br>  }<br><br>  mutex_unlock(&amp;memory_lock);<br><br>  // Return 8 bytes written<br>  return sizeof(u64);<br>}</pre><h4>Concurrency and Safety</h4><p>Modern systems are highly parallel. Unlike the single-byte drivers of the past, a modern driver must handle multiple programs accessing it at once. We use a Mutex (memory_lock) to ensure that if two processes try to write to our 64-bit memory simultaneously, the data remains consistent and the kernel does not crash.</p><h4>Testing the Driver</h4><p>Now we can put all our code together in a memory.c file.</p><pre>#include &lt;linux/module.h&gt;<br>#include &lt;linux/init.h&gt;<br>#include &lt;linux/kernel.h&gt;     // pr_info(), pr_err()<br>#include &lt;linux/fs.h&gt;         // file_operations structure<br>#include &lt;linux/miscdevice.h&gt; // Modern registration API<br>#include &lt;linux/uaccess.h&gt;    // copy_to_user/copy_from_user<br>#include &lt;linux/mutex.h&gt;      // Standard for handling concurrency<br><br>MODULE_LICENSE(&quot;Dual BSD/GPL&quot;);<br>MODULE_AUTHOR(&quot;Your Name&quot;);<br>MODULE_DESCRIPTION(&quot;Modern 64-bit Memory Driver&quot;);<br><br>// Storage for 64-bit value<br>static u64 memory_value = 0;<br>// Lock to prevent race conditions<br>static DEFINE_MUTEX(memory_lock);<br><br>/**<br> * memory_read - Transfers data from Kernel to User Space<br> * Equivalent to &#39;fread&#39; or &#39;cat&#39; in User Space.<br> */<br>static ssize_t memory_read(struct file *filp, char __user *buf, size_t count, loff_t *f_pos)<br>{<br>  // If the user has already read the value, return 0 (End of File)<br>  if (*f_pos &gt; 0) return 0;<br><br>  mutex_lock(&amp;memory_lock);<br><br>  // Standard safe transfer to User Space buffer<br>  if (copy_to_user(buf, &amp;memory_value, sizeof(u64)))<br>  {<br>    mutex_unlock(&amp;memory_lock);<br>    return -EFAULT;<br>  }<br><br>  mutex_unlock(&amp;memory_lock);<br><br>  *f_pos += sizeof(u64);<br><br>  // Return 8 bytes read<br>  return sizeof(u64);<br>}<br><br>/**<br> * memory_write - Transfers data from User to Kernel Space<br> * Equivalent to &#39;fwrite&#39; or &#39;echo&#39; in User Space.<br> */<br>static ssize_t memory_write(struct file *filp, const char __user *buf, size_t count, loff_t *f_pos) {<br>  mutex_lock(&amp;memory_lock);<br><br>  // Standard safe transfer from User Space buffer<br>  if (copy_from_user(&amp;memory_value, buf, sizeof(u64)))<br>  {<br>    mutex_unlock(&amp;memory_lock);<br>    return -EFAULT;<br>  }<br><br>  mutex_unlock(&amp;memory_lock);<br><br>  // Return 8 bytes written<br>  return sizeof(u64);<br>}<br><br>// Link standard file operations to our functions<br>static const struct file_operations memory_fops =<br>{<br>  .owner = THIS_MODULE,<br>  // Link to our read function<br>  .read  = memory_read,<br>  // Link to our write function<br>  .write = memory_write,<br>};<br><br>// Modern registration structure<br>static struct miscdevice memory_dev =<br>{<br>  // Kernel assigns a free minor number<br>  .minor = MISC_DYNAMIC_MINOR,<br>  // Creates /dev/memory automatically<br>  .name  = &quot;memory&quot;,<br>  .fops  = &amp;memory_fops,<br>};<br><br>static int __init memory_init(void)<br>{<br>  // Register driver<br>  int ret = misc_register(&amp;memory_dev);<br><br>  if (ret)<br>  {<br>    pr_err(&quot;memory: Failed to register device\n&quot;);<br>    return ret;<br>  }<br><br>  pr_info(&quot;memory: Modern 64-bit driver loaded\n&quot;);<br>  return 0;<br>}<br><br>static void __exit memory_exit(void)<br>{<br>  // Unregister and clean up<br>  misc_deregister(&amp;memory_dev);<br>  pr_info(&quot;memory: Driver unloaded\n&quot;);<br>}<br><br>module_init(memory_init);<br>module_exit(memory_exit);</pre><p>To compile this module, the Makefile must be modified again to look like this:</p><pre>obj-m := memory.o</pre><p>The compilation command is the same as the previous sections:</p><pre>make -C /usr/src/linux-headers-$(uname -r) M=$(pwd modules)</pre><p>Before starting the testing, the file permissions should be modified:</p><pre>sudo chmod 666 /dev/memory</pre><p>Next, you will need to write four bytes to the device file /dev/memory. A simple way to do this is with the echo or printf the command:</p><pre>printf &quot;64-BITS!&quot; &gt; /dev/memory</pre><p>After writing, the device could be read using the catcommand:</p><pre>cat /dev/memory</pre><p>To finish the tutorial, unload/remove it from the kernel using the command:</p><pre>sudo rmmod memory</pre><h3>Next steps</h3><p>You can go to the second post about Linux Drivers:</p><p><a href="https://erickof.medium.com/modern-linux-drivers-2-communicating-with-user-space-char-device-using-c-classes-1f1629a24023">https://erickof.medium.com/modern-linux-drivers-2-communicating-with-user-space-char-device-using-c-classes-1f1629a24023</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed8ea4183496" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Yocto Project Tutorial 1: Baking a Minimal Linux Image from Scratch (2026 with Whinlatter)]]></title>
            <link>https://erickof.medium.com/yocto-project-tutorial-1-baking-a-minimal-linux-image-from-scratch-2026-with-whinlatter-0f691a9fc091?source=rss-1615d8d84c36------2</link>
            <guid isPermaLink="false">https://medium.com/p/0f691a9fc091</guid>
            <category><![CDATA[yoctoproject]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[software]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[Erick Andrés Obregón Fonseca]]></dc:creator>
            <pubDate>Thu, 08 Jan 2026 05:58:07 GMT</pubDate>
            <atom:updated>2026-01-13T06:05:32.058Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*cKu0dMYxUBScZbrYIIxVLg.jpeg" /></figure><h3>Introduction</h3><p>I have already written about this in the past, so I decided to write a new version using the latest version available in 2025.</p><p><a href="https://erickof.medium.com/yocto-project-tutorial-baking-a-minimal-linux-image-from-scratch-625b3e65f768">Yocto Project Tutorial: Baking a Minimal Linux Image from Scratch</a></p><h3>What is the Yocto Project?</h3><blockquote>The Yocto Project is an open-source collaboration project that helps you to create custom Linux-based systems regardless of the hardware architecture [1].</blockquote><p>The Yocto Project is not an embedded Linux distribution, it creates a custom one for you. The Yocto Project has had several releases since the last post. These are the latest five releases, but you can find them all in [2].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qf5PxpvilPqpJG43XloEZQ.png" /></figure><p>I strongly recommend that you read “<a href="https://docs.yoctoproject.org/what-i-wish-id-known.html">What I wish I’d known about Yocto Project</a>” to better understand the build process.</p><h3>Why should I use my own custom Linux image?</h3><p>General-purpose operating systems (OS) — such as Windows, macOS, or most Linux distributions —are designed for versatility, not specialization. They come with several background services, as well as pre-installed applications that we don’t need or will never use on our embedded systems. Every unnecessary package increases the attack surface of the device. In an era of strict cybersecurity regulations, maintaining a lean system is no longer optional; it is a requirement for compliance.</p><p>Building a custom Linux image allows us to install only the dependencies and software that we need. By selecting only the essential kernel modules, libraries, and drivers, you achieve several critical advantages:</p><ul><li>Maximize available RAM and storage for the primary application, which is crucial when deploying Edge AI models or high-frequency data processing on limited hardware.</li><li>Reduced Boot Times by removing unnecessary initialization scripts. Custom images can achieve “instant-on” performance, often booting in under two seconds.</li><li>Custom images enable deep integration with specific hardware features, such as hardware accelerators (NPUs/GPUs) or custom FPGA logic, without interference from generic OS power-management or scheduling policies.</li><li>A custom image enables “Read-Only” root filesystems and atomic update capabilities, ensuring the device remains resilient against corruption and is easily patched remotely via OTA updates.</li></ul><h3>Before we start</h3><h4>Environment</h4><p>Before starting to work with Yocto, we must make sure that we meet some requirements [2]:</p><ul><li>At least 140 GB of free disk space.</li><li>At least 32 GB of RAM (as much RAM and as many CPU cores as possible is strongly recommended to maximize build performance).</li><li>A supported Linux distribution (i.e. recent releases of Fedora, openSUSE, CentOS, Debian, or Ubuntu).</li><li>The OpenEmbedded build system should be able to run on any modern distribution that has the following versions for git 1.8.3.1 or greater, tar 1.28 or greater, python 3.9.0 or greater, gcc 10.1 or greater, and GNU make 4.0 or greater.</li></ul><h4>Installing dependencies</h4><p>First, we need to install the necessary packages to run Yocto. Let’s open a terminal and copy and paste the next line:</p><pre>sudo apt-get install build-essential chrpath cpio debianutils diffstat \<br>                     file gawk gcc git iputils-ping libacl1 locales \<br>                     python3 python3-git python3-jinja2 python3-pexpect \<br>                     python3-pip python3-subunit socat texinfo unzip \<br>                     wget xz-utils zstd</pre><p>You also need to ensure you have the <em>en_US.UTF-8</em> locale enabled:</p><pre>locale --all-locales | grep en_US.utf8</pre><p>You can reconfigure the <em>locales </em>package to add it.</p><pre>sudo dpkg-reconfigure locales</pre><h3>Cloning bitbake-setup</h3><p>Clone a copy of the <em>bitbake-setup</em> by using:</p><pre>git clone https://git.openembedded.org/bitbake</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*ocD-Ksp8oSayNNw2nwNg0g.png" /></figure><p>To set up the builds in a different top directory, we can optionally run this command:</p><pre>./bitbake/bin/bitbake-setup settings set --global default top-dir-prefix $HOME</pre><p>This will set up a top directory in <em>$HOME</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*hhY0RUqqHixU45cbs4gZyQ.png" /></figure><p>Now, we need to set up a build environment.</p><pre>./bitbake/bin/bitbake-setup init</pre><p>This is an interactive program and will ask you for some configurations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n0nbThNvKSHH9upx5bSHrw.png" /></figure><p>From the previous image, the options represent different combinations of Policy (what kind of OS) and Stability (how modern or tested the code is). Let’s first understand what Policy and Stability mean:</p><h4>1. The Distribution (Policy):</h4><ul><li><em>Poky:</em> This is the Yocto Project’s “Reference Distribution.” It is a complete, working example that includes default settings for things like UI, package management, and initialization.</li><li><em>OE-nodistro:</em> This comes from the OpenEmbedded-Core. It provides the tools and recipes, but has zero preset policy. You have to define your own distribution settings (like <em>DISTRO = “my-custom-os”</em> ) for it to work.</li></ul><h4>2. The Release (Stability):</h4><ul><li><em>Master:</em> The latest development branch. It contains the absolute latest features, but might have bugs or breakages because it is updated daily.</li><li><em>Whinlatter (v5.3):</em> A stable, tested release. It is the current active version (as of 2025/2026) used for production-grade work, where reliability is more important than having the newest experimental features.</li></ul><p>For our options, this means:</p><ol><li><em>oe-nodistro-master:</em> A bleeding-edge, minimal foundation. This is for expert developers working on the core of the OpenEmbedded build system itself.</li><li><em>oe-nodistro-whinlatter:</em> A stable bare-bones foundation with no pre-defined OS settings. This is for professional/commercial products where 100% control over the OS architecture is required.</li><li><em>poky-master:</em> The absolute latest version of the Poky reference OS.</li><li><em>poky-whinlatter:</em> A stable version of the Poky reference OS. This is ideal for learning, prototyping, and most projects. This is for testing new Yocto features or contributing code back to the Yocto Project.</li></ol><p>With that said:</p><ol><li>We choose a configuration (<em>poky-whinlatter</em>) and then <em>poky Poky</em>..</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mX3nRBvVifVZs2rwyYVa7A.png" /></figure><p>2. We choose a target eachine (<em>qemux86–64</em>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*bnj3-Lr0YQsVbi4RhRvTvw.png" /></figure><p>4. We finally choose a setup directory. We can keep the default option by pressing Enter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*MZdwN8b93jlofQJpc2k0Mw.png" /></figure><p>This will create a new Setup in the top directory (<em>$HOME/bitbake-builds/poky-whinlatter</em>). The directory contains:</p><ul><li>A <em>README</em>, describing the current configuration and showing some instructions.</li><li>A <em>build</em> directory, containing all the files created during the build.</li><li>A <em>layers</em> directory, containing the needed layers to build the Poky reference distribution.</li><li>A <em>config </em>directory, representing the current configuration used for this setup.</li></ul><h3>Baking our Image</h3><p>Once our image is built, an entire Linux distribution is created, including the toolchain.</p><p>We need to execute the script to configure the environment necessary for variables and commands of the Yocto Project, which is the <em>init-build-env</em> file. We run the build environment command:</p><pre>source $HOME/bitbake-builds/poky-whinlatter-poky-distro_poky-machine_qemux86-64/build/init-build-env</pre><p>Make sure to run this command every time you need to build or rebuild the image.</p><p>If we take a glance inside the <em>conf </em>folder, we can see some configuration files. For this tutorial, we are only interested in the <em>local.conf</em> file. This file is automatically modified by the <em>bitbake-config-build</em> command-line tool.</p><p>Finally, we can build our image. This process can take a while… from 2 to 6 hours… depending on your internet connection and the processing power of your workstation. But don’t be overwhelmed, thankfully, every time you make a change or add new recipes (a set of instructions for building packages), Yocto will simply rebuild the changes and not the entire project, making this process less time-consuming.</p><pre>bitbake core-image-sato</pre><p>You can rerun the command to see that it will only take a couple of minutes to build.</p><h3>Testing our Image</h3><p>Now, let’s test our image. We can start QEMU that is shipped with the Yocto Project.</p><pre>runqemu snapshot</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D4plBV4Nf6aQCPKoVOPJLw.png" /></figure><p>Now we are done.</p><p>Please let me know if you have any questions or errors, and I will help you. Feel free to reach out.</p><h3>References</h3><p>[1] “Yocto Project — It’s not an embedded Linux distribution — it creates a custom one for you”, Yoctoproject.org. [Online]. Available: <a href="https://www.yoctoproject.org/">https://www.yoctoproject.org/.</a> [Accessed: 03-Jan-2026].</p><p>[2] “Yocto Project Quick Build”, Yoctoproject.org. [Online]. Available: <a href="https://docs.yoctoproject.org/brief-yoctoprojectqs/index.html">https://docs.yoctoproject.org/brief-yoctoprojectqs/index.html</a>. [Accessed: 03-Jan-2026].</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f691a9fc091" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with RISC-V: PlatformIO and the Sipeed Longan Nano]]></title>
            <link>https://erickof.medium.com/getting-started-with-risc-v-platformio-and-the-sipeed-longan-nano-1ebc3dd606bb?source=rss-1615d8d84c36------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ebc3dd606bb</guid>
            <category><![CDATA[vscode]]></category>
            <category><![CDATA[microcontrollers]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[platformio]]></category>
            <category><![CDATA[risc-v]]></category>
            <dc:creator><![CDATA[Erick Andrés Obregón Fonseca]]></dc:creator>
            <pubDate>Thu, 17 Jul 2025 07:14:49 GMT</pubDate>
            <atom:updated>2025-07-17T07:14:49.463Z</atom:updated>
            <content:encoded><![CDATA[<p>The world of open-source hardware is growing fast, and at its heart is RISC-V (pronounced “RISK-Five”), a free and open instruction set architecture (ISA). If you want to try RISC-V on real silicon, the Sipeed Longan Nano is an excellent starting point. In this guide, you will learn how to set it up using PlatformIO (PIO) and create your first blink project in minutes.</p><h3>What is RISC-V?</h3><p>I recommend these two posts about RISC-V if you are not familiar with it:</p><ul><li><a href="https://medium.com/0xmachina/the-risc-v-instruction-set-open-standard-architecture-327c38ddca9f">The RISC-V Instruction Set Open Standard Architecture</a></li><li><a href="https://medium.com/@wadixtech/the-future-of-riscv-architecture-as-competitor-of-arm-design-8daaec3856c8">The Future of RISCV Architecture as Competitor of ARM Design</a></li></ul><h3>Get to know the Sipeed Longan Nano</h3><p>The Longan Nano is a compact development board built around the GD32VF103CBT6 microcontroller (MCU), powered by the Nuclei Bumblebee core that supports the RV32IMAC instruction set and ECLIC, a fast interrupt controller. This MCU features GigaDevice’s latest 32-bit RISC-V core. It’s an excellent choice for students, engineers, hobbyists, and tech enthusiasts looking to explore the latest in RISC-V technology. You can find the official instruction set documentation <a href="http://dl.sipeed.com/LONGAN/Nano/DOC">here</a>.</p><p>The chip has built-in 128 KB Flash memory, 32 KB SRAM, and rich peripheral support:</p><ul><li>4 × 16-bit general-purpose timers</li><li>2 × 16-bit basic timers</li><li>1 × 16-bit advanced timer</li><li>Watchdog timer</li><li>RTC and Systick</li><li>3 × USART, 2 × I2C, 3 × SPI</li><li>2 × I2S, 2 × CAN</li><li>1 × USBFS (OTG)</li><li>2 × 10-channel ADC</li><li>2 × DAC</li></ul><p>The Longan Nano is breadboard-friendly and comes equipped with:</p><ul><li>An onboard 8 MHz passive crystal</li><li>A 32.768 kHz low-speed crystal for RTC</li><li>A mini TF card slot</li><li>A modern USB Type-C interface</li></ul><p>Also, the pin map can be seen in the following image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3Est2Y-G3PAnKWA5.png" /><figcaption>Sipeed Longan Nano PIN Map. Retrieved from <a href="https://longan.sipeed.com/en/">https://longan.sipeed.com/en</a>.</figcaption></figure><h3>Setting Up PlatformIO IDE for VSCode</h3><p>Installation instructions for VSCide can be found on the PIO web page: <a href="https://platformio.org/install/ide?install=vscode">https://platformio.org/install/ide?install=vscode</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cwy-uTgxKhioUyy_OaCGqA.png" /></figure><p>The Sipeed Longan Nano official web page also offers instructions for PIO configuration in VSCode and the GD32V platform, but there have been some issues reported in different forums:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/0*rY9WNrvgwi1w2R-b.png" /></figure><p>We will do a workaround for it.</p><h3>Getting to Blinky</h3><p>This section is based on the tutorial from the <a href="https://longan.sipeed.com/en/get_started/blink.html">Sipeed Longan Nano Getting Started webpage</a>, but I will provide a workaround to make the project work.</p><p>First, let’s create a project by clicking on the “PIO” logo, then “Create New Project”, and “+ New Project”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rGJY3OYlnmOeQ4DBFTRtkA.png" /></figure><p>Then you can configure the project as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*WbcE603yzf17iXfap2ReDw.png" /></figure><p>It will start the project creation, and you will see the following project structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dH17cNDsHTgydMhA5NEC_Q.png" /></figure><p>We need to create a new directory called <em>packages</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N6jbcv7rCoA_SNYJcqhzRw.png" /></figure><p>Then go to <a href="https://sourceforge.net/projects/platformio-storage/files/packages/">https://sourceforge.net/projects/platformio-storage/files/packages/</a>, download the following packages:</p><ul><li>toolchain-gd32v</li><li>tool-openocd-gd32v</li><li>tool-gd32vflash</li></ul><p>and unzip them in the created folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C91_7zewIX42Nmtt7ZwNKg.png" /></figure><p>Now that we have those files in place, we can replace the content of the <em>platformio.ini</em> file with:</p><pre>[env:sipeed-longan-nano]<br>platform = gd32v<br>board = sipeed-longan-nano<br>framework = arduino<br>platform_packages = framework-arduino-gd32v @ https://github.com/sipeed/Longduino.git<br>                    toolchain-gd32v @ file://packages/toolchain-gd32v<br>                    tool-openocd-gd32v @ file://packages/tool-openocd-gd32v<br>                    tool-gd32vflash @ file://packages/tool-gd32vflash<br>monitor_speed = 115200<br>upload_protocol = dfu</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YpAiUpYIiVmdBnovoAYu1w.png" /></figure><p>In <em>src/main.cpp</em>, you can replace the content with:</p><pre>#include &lt;Arduino.h&gt;<br><br><br>void setup()<br>{<br>  // Initialize LED digital pin as an output.<br>  pinMode(LED_BUILTIN, OUTPUT);<br>}<br><br>void loop()<br>{<br>  // Turn the LED on (HIGH is the voltage level)<br>  digitalWrite(LED_BUILTIN, HIGH);<br>  // Wait for a second<br>  delay(1000);<br>  // Turn the LED off by making the voltage LOW<br>  digitalWrite(LED_BUILTIN, LOW);<br>  // Wait for a second<br>  delay(1000);<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0f3LnTHnpl0IYRgLHTi6ww.png" /></figure><p>Once you save the files, PIO will start configuring the project and should see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H59p3x1t3huOtmYAqO2Ypg.png" /></figure><p>In the PIO extension, you can click “Build”, and the compilation must pass.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fg2_op3KPCBQTqtNOkKrzw.png" /></figure><h3>Connect to the development board</h3><p>To enter boot mode, hold down the <em>BOOT</em> key, then press the <em>RESET</em> key to restart the development board, and then release the <em>BOOT</em> key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*XTmsdQrfJudbR2e24XVl_g.png" /></figure><p>Since we’ll use USB DFU, we need to install the libusb driver for the first time of usage. It is recommended to install the WinUSB driver via <a href="https://github.com/pbatard/libwdi/releases/download/b721/zadig-2.4.exe">Zadig</a>. Open Zadig after successful download, select “GD32V” in the drop-down bar, replace the driver with “WinUSB”, click the “Replace” button, and the replacement will succeed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/0*pN4Jk9kRQUPibAsP.png" /></figure><p>More information about the protocols can be found at <a href="https://longan.sipeed.com/en/get_started/blink.html#connect-to-the-development-board">https://longan.sipeed.com/en/get_started/blink.html#connect-to-the-development-board</a>.</p><h3>Upload the Code</h3><p>Now that everything is configured, connect your board to your computer. In the PIO extension, you can click “Upload”, and you’ll see the following output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZXmMqmELYdddUpMm_P2G5w.png" /></figure><p>You should see the built-in LED blinking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*UqeLXM-x3smaI00Teq64Vg.gif" /></figure><h3>Conclusions</h3><p>The Sipeed Longan Nano is more than just an ostentatiously attractive development board with a built-in RGB LED; it is a gateway into the open world of RISC-V development. Whether you are a student, hobbyist, or just curious about modern computer architecture, RISC-V is worth exploring, and PIO makes it easier than ever to dive in.</p><p>Let me know in the comments if the project works for you or if you’ve faced any issues, and I’ll update the post accordingly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ebc3dd606bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Yocto Project Tutorial: Baking a Minimal Linux Image from Scratch]]></title>
            <link>https://erickof.medium.com/yocto-project-tutorial-baking-a-minimal-linux-image-from-scratch-625b3e65f768?source=rss-1615d8d84c36------2</link>
            <guid isPermaLink="false">https://medium.com/p/625b3e65f768</guid>
            <category><![CDATA[yoctoproject]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[software]]></category>
            <category><![CDATA[computer-engineering]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <dc:creator><![CDATA[Erick Andrés Obregón Fonseca]]></dc:creator>
            <pubDate>Mon, 02 Nov 2020 06:02:28 GMT</pubDate>
            <atom:updated>2026-01-08T06:00:18.884Z</atom:updated>
            <content:encoded><![CDATA[<h3>Yocto Project Tutorial 1: Baking a Minimal Linux Image from Scratch (2020 with Poky Dunfell)</h3><h3>Updated version</h3><p><a href="https://erickof.medium.com/yocto-project-tutorial-1-baking-a-minimal-linux-image-from-scratch-2026-with-whinlatter-0f691a9fc091">Yocto Project Tutorial 1: Baking a Minimal Linux Image from Scratch (2026 with Whinlatter)</a></p><h3>Introduction</h3><p>Even though I am still a student, I have always wanted to share a little of what I have acquired throughout my university studies. This is why I’ve decided to write this, my first blog. In this case, I bring a tool that I learned to use in the Introduction to Embedded Systems course and that I found very interesting.</p><h3>What is the Yocto Project?</h3><blockquote>The Yocto Project is an open-source collaboration project that helps you to create custom Linux-based systems regardless of the hardware architecture [1].</blockquote><p>As they say on their page, the Yocto Project is not an embedded Linux distribution; instead, it creates a custom one for you.</p><p>The Yocto Project has several releases. I am mentioning the last five releases, but you can find them all in [2].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*wKgRoG8c7nFSfCxYksrRlw.png" /></figure><p>As you can see, the Hardknott version has yet to be released (at least by the time I wrote this post).</p><blockquote>The Yocto Project through the OpenEmbedded build system provides an open source development environment targeting the ARM, MIPS, PowerPC and x86 architectures for a variety of platforms including x86–64 and emulated ones. You can use components from the Yocto Project to design, develop, build, debug, simulate, and test the complete software stack using Linux, the X Window System, GTK+ frameworks, and Qt frameworks [3].</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/0*IaJv6IvY6ybNZGBH.png" /><figcaption>The Yocto Project Development Environment. Taken from [3].</figcaption></figure><p>For this tutorial, we will use <em>Poky Dunfell </em>because I have worked with it before and had no problems.</p><h3>Why should I use my own custom Linux image?</h3><p>General-purpose operating systems, such as Windows, macOS, or most Linux distributions, have several tasks to run in the background, as well as multiple installed applications that we don’t need or will never use on our embedded systems. All these reasons, together with the limited resources of our systems, make these operating systems inefficient or excessive for our poor hardware. Think that you don’t need a text editor, an office package, or a PDF reader in your embedded system if you will work with an IoT device.</p><p>Building our own operating systems allows us to install only the dependencies and software that we need. This makes it easier for us to better control and take advantage of our limited hardware and make our system more efficient by executing only the tasks it needs.</p><h3>Before we start</h3><h4>Environment</h4><p>Before starting to work with Yocto, we must make sure that we meet some requirements:</p><ul><li>A supported Linux version (like Fedora, OpenSUSE, CentOS, Debian, or Ubuntu). You can check them in [4].</li><li>The OpenEmbedded build system should be able to run on any modern distribution that has the following versions for Git 1.7.8 or greater, tar 1.24 or greater, and Python 2.7.3 or greater [4].</li><li>At least 50 GB of free disk space for image creation.</li></ul><h4>Installing dependencies</h4><p>First, we need to install the necessary packages to run Yocto. Let’s open a terminal and copy and paste the next line:</p><blockquote>sudo apt-get install gawk wget git-core diffstat unzip texinfo gcc-multilib build-essential chrpath socat libsdl1.2-dev xterm</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*JMZqFD0lqxf5a7ZES-meiA.png" /></figure><p>In my case, I already had all the packages installed.</p><h4>Installing QEmu</h4><p>This is the easiest part; you only need to run:</p><blockquote>sudo apt-get install qemu</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*37bzyZwQWBmY2UPoUb3qdA.png" /></figure><h4>Downloading Poky Dunfell</h4><p>There are two options to download <em>Poky Dunfell</em>. The first one is to go to this <a href="http://downloads.yoctoproject.org/releases/yocto/yocto-3.1.2/poky-dunfell-23.0.2.tar.bz2">link</a> and download the <em>tar.bz</em> compressed file, or type in a terminal:</p><blockquote>wget <a href="http://downloads.yoctoproject.org/releases/yocto/yocto-3.1.2/poky-dunfell-23.0.2.tar.bz2">http://downloads.yoctoproject.org/releases/yocto/yocto-3.1.2/poky-dunfell-23.0.2.tar.bz2</a></blockquote><p>I will download it to my user folder. It could take a while depending on your connection speed, so be patient.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*MtkdVrNdmC8bCDlMqIPCLA.png" /></figure><p>Now, we need to unzip the downloaded file.</p><blockquote>tar -xvf poky-dunfell-23.0.2.tar.bz2</blockquote><p>This will create a new folder called <em>poky-dunfell-23.0.2</em> (you can change the name if you want, but it is not necessary). Now let’s enter the directory and show its content.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*vphy3-txZig6ouiODgFp2w.png" /></figure><h3>Baking our Image</h3><p>Now, we will create a couple of directories to work with. The first is a folder where Yocto will download all our packages and dependencies (<em>downloads</em> folder), and the second one will be used for our image (<em>qemu-arm</em> folder). You can name them as you want.</p><blockquote>mkdir downloads<br>mkdir qemu-arm</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/0*YR5YRvRKO0CBx1n7" /></figure><p>We need to execute the script to configure the environment necessary for variables and commands of the Yocto Project, which is the <em>oe-init-build-env</em> file. This will go into the <em>qemu-arm</em> folder.</p><blockquote>. oe-init-build-env qemu-arm</blockquote><p>Make sure to run this command every time you need to build or rebuild the image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/889/1*aDKD98PmPRNUXKxLm4ysaQ.png" /></figure><p>If we take a glance inside the <em>conf</em> folder, we can see some configuration files. For this tutorial, we are only interested in the <em>local.conf </em>file, where we can set the machine architecture and the download folder path. In this, we need to add the following lines to the end of the file and change &lt;user&gt; for your user:</p><blockquote>DL_DIR ?= “/home/&lt;user&gt;/poky-dunfell-23.0.2/downloads”<br>INHERIT += “rm_work”<br>MACHINE ?= “qemuarm”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*nzKdaw3zUw4QVdaV3uFXnA.png" /></figure><p>You could use other test architectures that come <em>local.conf</em> file like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/0*kU2L6DuJDdRtResy" /></figure><p>Comments are written with <em>#</em> at the beginning. Another setting you can use is the default directory for downloads.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*Ci5JseN0ezrGnXsQ5pqf5Q.png" /></figure><p>Finally, we can build our image. This process can take a while… 2–6 hours… depending on your internet connection and the processing power of your workstation (in this case, your computer). But don’t be overwhelmed, thankfully, every time you make a change or add new recipes (set of instructions for building packages [5]), Yocto will simply rebuild the changes and not the entire project, making this process less time-consuming.</p><blockquote>bitbake core-image-minimal</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/0*FdlYFlMZYn43T9W_" /></figure><p>You can rerun the command to see that it will only take a couple of minutes to build.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/0*s5tipmN9lyF1uWKc" /></figure><h3>Testing our Image</h3><p>Now, let’s test our image. Since our image is not graphic but console, we must specify it so that it does not produce an error.</p><blockquote>runqemu qemuarm nographic</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*QtTIIU69CaSXXb97xHciKA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/1*mx-o6oyUgu6dV6SCwWeDBg.png" /></figure><p>Now, type <em>root,</em> and we are done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*_LVxQjFiOivgtAWrFSjonA.png" /></figure><h3>Bibliographic References</h3><p>[1] “Yocto Project — It’s not an embedded Linux distribution — it creates a custom one for you”, Yoctoproject.org. [Online]. Available: https://www.yoctoproject.org/. [Accessed: 23- Oct- 2020].</p><p>[2] “Releases — Yocto Project”, Wiki.yoctoproject.org. [Online]. Available: https://wiki.yoctoproject.org/wiki/Releases. [Accessed: 23- Oct- 2020].</p><p>[3] ”Yocto Project Quick Start”, Yoctoproject.org. [Online]. Available: <a href="https://www.yoctoproject.org/docs/1.8/yocto-project-qs/yocto-project-qs.html#:~:text=You%20need%20these%20things%20to,%2C%20Debian%2C%20or%20Ubuntu">https://www.yoctoproject.org/docs/1.8/yocto-project-qs/yocto-project-qs.html</a>. [Accessed: 25- Oct- 2020].</p><p>[4] ”Yocto Project Reference Manual”, Yoctoproject.org. [Online]. Available: <a href="https://www.yoctoproject.org/docs/1.8/ref-manual/ref-manual.html#detailed-supported-distros">https://www.yoctoproject.org/docs/1.8/ref-manual/ref-manual.html</a>. [Accessed: 25- Oct- 2020].</p><p>[5] “Yocto Project Development Manual”, Yoctoproject.org. [Online]. Available: <a href="https://www.yoctoproject.org/docs/1.6/dev-manual/dev-manual.html">https://www.yoctoproject.org/docs/1.6/dev-manual/dev-manual.html</a>. [Accessed: 26- Oct- 2020].</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=625b3e65f768" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tutoriel Yocto Project: Baking une image Linux minimale à partir de zéro]]></title>
            <link>https://erickof.medium.com/tutoriel-yocto-project-baking-une-image-linux-minimale-%C3%A0-partir-de-z%C3%A9ro-c43955d670b?source=rss-1615d8d84c36------2</link>
            <guid isPermaLink="false">https://medium.com/p/c43955d670b</guid>
            <category><![CDATA[computer-engineering]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[software]]></category>
            <category><![CDATA[yoctoproject]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <dc:creator><![CDATA[Erick Andrés Obregón Fonseca]]></dc:creator>
            <pubDate>Mon, 02 Nov 2020 06:02:27 GMT</pubDate>
            <atom:updated>2026-01-08T06:02:07.199Z</atom:updated>
            <content:encoded><![CDATA[<h3>Tutoriel Yocto Project 1: Baking une image Linux minimale à partir de zéro (2020 avec Poky Dunfell)</h3><h3>Version mise à jour (en anglais)</h3><p><a href="https://erickof.medium.com/yocto-project-tutorial-1-baking-a-minimal-linux-image-from-scratch-2026-with-whinlatter-0f691a9fc091">Yocto Project Tutorial 1: Baking a Minimal Linux Image from Scratch (2026 with Whinlatter)</a></p><h3>Introduction</h3><p>Même si je suis encore un étudiant, j’ai toujours voulu partager un peu les connaissances que j’ai acquises tout au long de mes études universitaires. C’est pourquoi j’ai décidé d’écrire ceci, mon premier blog. C’est pourquoi j’apporte un outil que j’ai appris à utiliser dans le cours d’Introduction aux Systèmes Embarqués et que j’ai trouvé très intéressant.</p><h3>Qu’est-ce que c’est, le Yocto Project ?</h3><blockquote>Le projet Yocto est un projet collaboratif open source qui vous aide à créer des systèmes personnalisés basés sur Linux, indépendamment de l’architecture du hardware[1].</blockquote><p>Comme ils le disent sur leur page, le Yocto Project n’est pas une distribution Linux embarqué, mais il en crée une personnalisée pour vous.</p><p>Il existe plusieurs versions de Yocto Project. Je mentionnerai les cinq dernières versions, mais vous pouvez toutes les trouver dans [2].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*wKgRoG8c7nFSfCxYksrRlw.png" /></figure><p>Comme vous pouvez voir, la version Hardnott n’a pas encore été publiée (du moins au moment où j’ai écrit ce post).</p><blockquote>Le Yocto Project fournit, à travers le système de construction OpenEmbedded, un environnement de développement open source ciblant les architectures ARM, MIPS, PowerPC et x86 pour une variété de plates-formes, y compris x86–64 et émulées. Vous pouvez utiliser les componsants du Yocto Project pour concevoir, développer, construire, déboguer, simuler et tester la pile du software complète en utilisant Linux, le système X Window, les frameworks GTK+ et les frameworks Qt [3].</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/0*IaJv6IvY6ybNZGBH.png" /><figcaption>The Yocto Project Development Environment. Taken from [3].</figcaption></figure><p>Pour ce tutoriel, nous utiliserons <em>Poky Dunfell</em> car j’ai déjà bossé avec ça et je n’ai eu aucun problème.</p><h3>Pourquoi je devrais utiliser ma propre image Linux personnalisée ?</h3><p>Les systèmes d’exploitation à usage général, tels que Windows, macOS ou la plupart des distributions Linux, ont plusieurs tâches à exécuter en arrière-plan, ainsi que plusieurs applications installées dont nous n’avons pas besoin ou que nous n’utiliserons jamais sur ces systèmes embarqués. Toutes ces raisons, ainsi que les ressources limitées de nos systèmes, le fait de rendre ces systèmes d’exploitation inefficaces ou excessifs pour notre pauvre hardware. Dites-vous que vous n’aurez pas besoin d’un éditeur de texte, d’un package bureautique ou d’un lecteur PDF dans son système embarqué si vous avez l’intention de bosser avec un appareil IoT.</p><p>Construire nos propres systèmes d’exploitation nous permet d’installer uniquement les dépendances et le software dont nous avons besoin. Cela nous permet de mieux contrôler et de tirer parti de notre hardware limité et de rendre notre système plus efficace en n’exécutant que les tâches dont il a besoin.</p><h3>Avant de commencer</h3><h4>Environnement</h4><p>Avant de commencer à bosser avec Yocto, nous devons assurer que nous remplissons certaines conditions:</p><ul><li>Une version Linux prise en charge (comme Fedora, OpenSUSE, CentOS, Debian ou Ubuntu). Vous pouvez les vérifier dans [4].</li><li>Le système de construction OpenEmbedded devrait pouvoir fonctionner sur n’importe quelle distribution moderne qui a les versions suivantes pour Git 1.7.8 ou supérieur, tar 1.24 ou supérieur et Python 2.7.3 ou supérieur [4].</li><li>Au moins 50 GB d’espace disque disponible pour la création d’images.</li></ul><h4>Installer les dépendances</h4><p>Tout d’abord, nous devons installer les packages nécessaires pour exécuter Yocto. Ouvrons un terminal et copions et collons la ligne suivante:</p><blockquote>sudo apt-get install gawk wget git-core diffstat unzip texinfo gcc-multilib build-essential chrpath socat libsdl1.2-dev xterm</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*JMZqFD0lqxf5a7ZES-meiA.png" /></figure><p>Dans mon cas, j’avais déjà tous les packages installés.</p><h4>Installer QEmu</h4><p>C’est la partie la plus simple, il vous suffit d’exécuter:</p><blockquote>sudo apt-get install qemu</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*37bzyZwQWBmY2UPoUb3qdA.png" /></figure><h4>Téléchargement de Poky Dunfell</h4><p>Il y a deux options pour télécharger <em>Poky Dunfell</em>. La première es d’aller sur ce <a href="http://downloads.yoctoproject.org/releases/yocto/yocto-3.1.2/poky-dunfell-23.0.2.tar.bz2">lien</a> et de télécharger le ficher compressé <em>tar.bz</em> ou de taper dans un terminal:</p><blockquote>wget <a href="http://downloads.yoctoproject.org/releases/yocto/yocto-3.1.2/poky-dunfell-23.0.2.tar.bz2">http://downloads.yoctoproject.org/releases/yocto/yocto-3.1.2/poky-dunfell-23.0.2.tar.bz2</a></blockquote><p>Je vais le télécharger dans mon dossier utilisateur. Cela peut prendre un certain temps en fonction de la vitesse de votre connexion, alors soyez patient.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*MtkdVrNdmC8bCDlMqIPCLA.png" /></figure><p>Maintenant, nous avons besoin de décompresser le fichier téléchargé.</p><blockquote>tar -xvf poky-dunfell-23.0.2.tar.bz2</blockquote><p>Cela créera un nouveau dossier appelé <em>poky-dunfell-23.0.2</em> (vous pouvez changer le nom si vous souhaitez, mais ce n’est pas nécessaire). Maintenant, entrons dans le dossier et montrons son contenu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*vphy3-txZig6ouiODgFp2w.png" /></figure><h3>Baking notre Image</h3><p>Maintenant, nous allons créer quelques dossiers pour bosser. Le premier est un dossier où Yocto téléchargera tous nos packages et nos dépendances (dossier <em>downloads</em>), et le second sera utilisé pour notre image (dossier <em>qemu-arm</em>). Vous pouvez les nommer comme vous souhaitez.</p><blockquote>mkdir downloads<br>mkdir qemu-arm</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/0*YR5YRvRKO0CBx1n7" /></figure><p>Nous devons exécuter le script pour configurer l’environnement nécessaire aux variables et aux commandes du Yocto Project, c’est le fichier <em>oe-init-build-env</em>. Cela ira dans le dossier <em>qemu-arm</em>.</p><blockquote>. oe-init-build-env qemu-arm</blockquote><p>Assurez-vous d’exécuter cette commande chaque fois que vous devez construire ou reconstruire l’image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/889/1*aDKD98PmPRNUXKxLm4ysaQ.png" /></figure><p>Si nous jetons un coup d’œil dans le dossier <em>conf</em>, nous pouvons voir quelques fichiers de configuration. Pour ce tutoriel, nous nous intéressons uniquement au fichier <em>local.conf</em> où nous pouvons définir l’architecture de la machine et le chemin du dossier de téléchargement. En cela, nous devons ajouter les lignes suivantes à la fin du fichier en modifiantt &lt;user&gt; pour votre utilisateur:</p><blockquote>DL_DIR ?= “/home/&lt;user&gt;/poky-dunfell-23.0.2/downloads”<br>INHERIT += “rm_work”<br>MACHINE ?= “qemuarm”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*nzKdaw3zUw4QVdaV3uFXnA.png" /></figure><p>Vous pourriez utiliser d’autres architectures de test fournies dans le fichier <em>local.conf</em> comme:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/0*kU2L6DuJDdRtResy" /></figure><p>Il y a un # devant chaque commentaire. Vous pouvez également utiliser le dossier par défaut pour les téléchargements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*Ci5JseN0ezrGnXsQ5pqf5Q.png" /></figure><p>Enfin, nous pouvons construire notre image. Ce processus peut prendre un certain temps… 2 à 6 heures… selon votre connexion Internet et la puissance de traitement de votre workstation (dans ce cas, votre ordinateur). Mais ne soyez pas submergé, car heureusement, chaque fois que vous apportez un changement ou ajoutez de nouvelles recettes (ensemble d’instructions pour la construction de packages [5]), Yocto va simplement reconstruire les changements et non l’ensemble du projet, rendant ce processus moins chronophage.</p><blockquote>bitbake core-image-minimal</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/0*FdlYFlMZYn43T9W_" /></figure><p>Vous pouvez réexécuter la commande pour voir que la construction ne prendra plus que quelques minutes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/0*s5tipmN9lyF1uWKc" /></figure><h3>Tester notre Image</h3><p>Maintenant, testons notre image. Puisque notre image n’est pas graphique mais console, nous devons la spécifier pour qu’elle ne produise pas d’erreur.</p><blockquote>runqemu qemuarm nographic</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*QtTIIU69CaSXXb97xHciKA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/1*mx-o6oyUgu6dV6SCwWeDBg.png" /></figure><p>Maintenant, tapez <em>root</em>, et nous avons terminé.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*_LVxQjFiOivgtAWrFSjonA.png" /></figure><h3>Références Bibliographiques</h3><p>[1] “Yocto Project — It’s not an embedded Linux distribution — it creates a custom one for you”, Yoctoproject.org. [En ligne]. Disponible: <a href="https://www.yoctoproject.org/">https://www.yoctoproject.org/.</a> [Accédé: 23- Oct- 2020].</p><p>[2] “Releases — Yocto Project”, Wiki.yoctoproject.org. [En ligne]. Disponible: <a href="https://wiki.yoctoproject.org/wiki/Releases.">https://wiki.yoctoproject.org/wiki/Releases.</a> [Accédé: 23- Oct- 2020].</p><p>[3] ”Yocto Project Quick Start”, Yoctoproject.org. [En ligne]. Disponible: <a href="https://www.yoctoproject.org/docs/1.8/yocto-project-qs/yocto-project-qs.html#:~:text=You%20need%20these%20things%20to,%2C%20Debian%2C%20or%20Ubuntu">https://www.yoctoproject.org/docs/1.8/yocto-project-qs/yocto-project-qs.html</a>. [Accédé: 25- Oct- 2020].</p><p>[4] ”Yocto Project Reference Manual”, Yoctoproject.org. [En ligne]. Disponible: <a href="https://www.yoctoproject.org/docs/1.8/ref-manual/ref-manual.html#detailed-supported-distros">https://www.yoctoproject.org/docs/1.8/ref-manual/ref-manual.html</a>. [Accédé: 25- Oct- 2020].</p><p>[5] “Yocto Project Development Manual”, Yoctoproject.org. [En ligne]. Disponible: <a href="https://www.yoctoproject.org/docs/1.6/dev-manual/dev-manual.html">https://www.yoctoproject.org/docs/1.6/dev-manual/dev-manual.html</a>. [Accédé: 26- Oct- 2020].</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c43955d670b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>