<?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 Daniel Gallagher on Medium]]></title>
        <description><![CDATA[Stories by Daniel Gallagher on Medium]]></description>
        <link>https://medium.com/@pdanielgallagher?source=rss-102b97b1e306------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8pixnWgXTXvvSV1ONsXZvg.jpeg</url>
            <title>Stories by Daniel Gallagher on Medium</title>
            <link>https://medium.com/@pdanielgallagher?source=rss-102b97b1e306------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 19:05:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pdanielgallagher/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[Bluetooth Low Energy with Rust]]></title>
            <link>https://medium.com/@pdanielgallagher/bluetooth-low-energy-with-rust-f4a4fc329d75?source=rss-102b97b1e306------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4a4fc329d75</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[bluetooth]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[embedded]]></category>
            <dc:creator><![CDATA[Daniel Gallagher]]></dc:creator>
            <pubDate>Thu, 27 Sep 2018 11:52:09 GMT</pubDate>
            <atom:updated>2018-10-02T04:00:19.735Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*XxM_d_SegUfGf5_I.jpeg" /><figcaption>BlueNRG-MS on the Nuclean IDB05A1 Shield</figcaption></figure><h3>Bluetooth on Embedded Rust</h3><p>A core component of my personal project is to have two devices communicating wirelessly, and (at the time I started working on this) there were no “no-std” Rust Bluetooth crates available. So I started to write my own. I had already chosen to work on the <a href="https://dev-219-design-llc.pantheonsite.io/rust-on-the-stmicro-nucleo/">Nucleo</a>, and to use the <a href="https://www.st.com/en/ecosystems/x-nucleo-idb05a1.html">IDB05A1</a> shield, which contains a <a href="https://www.st.com/en/wireless-connectivity/bluenrg-ms.html">BlueNRG-MS</a> module.</p><p>This development effort resulted in two crates:</p><ul><li>A no-std Rust SPI <a href="https://crates.io/crates/bluenrg">driver</a> for the BlueNRG-MS (and older BlueNRG) module.</li><li>A device-independent pure-Rust <a href="https://crates.io/crates/bluetooth-hci">implementation</a> of the Bluetooth Host-Controller Interface.</li></ul><h3>Bluetooth HCI</h3><p>The bluetooth-hci crate implements the host-controller interface portion of the Bluetooth specification. To date, this is only a partial implementation (only supporting the commands that BlueNRG-MS supports), but the framework is in place for extending it to implement the rest of the specification.</p><p>By default, the crate implements version 4.1 of the Bluetooth specification, but has features for versions 4.2 and 5.0 as well:</p><pre>[dependencies.bluetooth-hci]<br>features = [&quot;version-5-0&quot;]</pre><h4>Implementing Controller</h4><p>The Bluetooth-HCI is written on top of the <a href="https://docs.rs/bluetooth-hci/0.0.3/bluetooth_hci/trait.Controller.html">Controller</a> trait, which determines how the host reads bytes from and writes bytes to the controller. It has three methods and three associated types:</p><ul><li><a href="https://docs.rs/bluetooth-hci/0.0.3/bluetooth_hci/trait.Controller.html#associatedtype.Error">type Error</a>. This is the type of errors from the underlying communication bus.</li><li><a href="https://docs.rs/bluetooth-hci/0.0.3/bluetooth_hci/trait.Controller.html#associatedtype.Header">type Header</a>. This is the type of header to send before the payloads. This should be <a href="https://docs.rs/bluetooth-hci/0.0.3/bluetooth_hci/host/uart/struct.CommandHeader.html">bluetooth_hci::uart::CommandHeader</a>. This associated type may be removed in the future.</li><li><a href="https://docs.rs/bluetooth-hci/0.0.3/bluetooth_hci/trait.Controller.html#associatedtype.Vendor">type Vendor</a>. This is a trait that defines vendor-specific extensions that the HCI may use:</li><li><a href="https://docs.rs/bluetooth-hci/0.0.3/bluetooth_hci/trait.Vendor.html#associatedtype.Status">type Status</a>. This is an enumeration of vendor-specific status codes.</li><li><a href="https://docs.rs/bluetooth-hci/0.0.3/bluetooth_hci/trait.Vendor.html#associatedtype.Event">type Event</a>. This is the type of vendor-specific events.</li><li><a href="https://docs.rs/bluetooth-hci/0.0.3/bluetooth_hci/trait.Controller.html#tymethod.write">fn write</a>. Writes a header and payload to the controller in a single transaction.</li><li><a href="https://docs.rs/bluetooth-hci/0.0.3/bluetooth_hci/trait.Controller.html#tymethod.read_into">fn read_into</a>. Reads available bytes from the controller into a caller-supplied buffer.</li><li><a href="https://docs.rs/bluetooth-hci/0.0.3/bluetooth_hci/trait.Controller.html#tymethod.peek">fn peek</a>. Returns a byte that will soon be returned by a call to read_into. Implementations should support peeking up to 5 bytes ahead.</li></ul><p>Controller operates at a byte level. To read Bluetooth <em>events</em> from the device, you need to use <a href="https://docs.rs/bluetooth-hci/0.0.3/bluetooth_hci/host/uart/trait.Hci.html">bluetooth_hci::uart::Hci</a>, which is an extension trait to Controller. So you literally just need to</p><pre>use bluetooth_hci::uart::Hci;</pre><p>to be able to read Bluetooth events. You will need to specify the particular type of vendor-specific events, errors, and status codes that may occur. But, via the magic of type inference, you don’t need to specify any of these in your Controller implementation.</p><h3>BlueNRG-MS</h3><p>The BlueNRG crate provides an embedded-hal driver for the STMicro BlueNRG Bluetooth processor. It communicates on a SPI bus, and needs a few other GPIOs for various purposes. It also needs a dedicated buffer in memory where it can store bytes received from the controller before the application reads them (so it can implement peek, and efficiently read entire messages).</p><p>To initialize a <a href="https://docs.rs/bluenrg/0.0.3/bluenrg/struct.BlueNRG.html">BlueNRG</a> instance, you need something that implements <a href="https://docs.rs/embedded-hal/0.2.1/embedded_hal/blocking/spi/trait.Transfer.html">embedded_hal::blocking::spi::Transfer</a> and <a href="https://docs.rs/embedded-hal/0.2.1/embedded_hal/blocking/spi/trait.Write.html">Write</a>, an input GPIO so the controller can notify the host when data is ready, and two output GPIOs: one to select the chip (so multiple chips can talk on one SPI bus), and one to reset the controller. Using the <a href="https://crates.io/crates/stm32f30x">STM32F30x</a> crate, this looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c18fd1e438da898715dea7d41256572/href">https://medium.com/media/4c18fd1e438da898715dea7d41256572/href</a></iframe><p>Note that BlueNRG does not take ownership of a SPI bus. However, the BlueNRG type is dependent on a concrete SPI type. Rust’s robust type inference lets us elide that type information, since it is determined later in the code. To communicate with the chip (to do anything other than reset it), you must use its <a href="https://docs.rs/bluenrg/0.0.3/bluenrg/struct.BlueNRG.html#method.with_spi">with_spi</a> method:</p><pre>bnrg.with_spi(&amp;mut spi, |c| {<br>    block!(c.read_local_version_information())<br>});</pre><p>with_spi takes a handle to a SPI bus and a block to execute. The block is passed an <a href="https://docs.rs/bluenrg/0.0.3/bluenrg/struct.ActiveBlueNRG.html">ActiveBlueNRG</a> struct, which implements bluetooth_hci::Controller, and has all of the BlueNRG vendor-specific commands available.</p><p><em>Note: The BlueNRG has its own firmware that can be updated. This crate is not for writing firmware that runs on the BlueNRG itself. It is for writing firmware on a host processor that communicates with the BlueNRG over SPI.</em></p><h3>Sending Commands to the Controller</h3><p>Once the BlueNRG is initialized, you must use its with_spi method to get the corresponding ActiveBlueNRG struct. You then use the ActiveBlueNRG to send commands to the chip. All of the methods are defined in traits that are implemented for all bluetooth_hci::Controller implementors (and therefore for ActiveBlueNRG). Vendor-specific commands are implemented in extension traits as well.</p><p>All of the commands return <a href="https://docs.rs/nb/0.1.1/nb/type.Result.html">nb::Result</a> structs, so they can be used in an embedded asynchronous environment. Internally, they use the blocking SPI commands from embedded-hal, so they are not completely asynchronous. However, if the BlueNRG is not ready or if its internal buffers are full, your code does not have to block while those conditions are cleared.</p><h3>Standard Bluetooth Commands</h3><p>The Bluetooth specification defines a number of HCI commands that the host may use to communicate with the controller.</p><p><strong><em>Work in progress! </em></strong><em>The bluetooth-hci crate is intended to support the full Bluetooth specification (versions 4.1, 4.2, and 5.0). However, currently only commands and events supported by the BlueNRG are supported.</em></p><p>All of the commands are defined in the <a href="https://docs.rs/bluetooth-hci/0.0.3/bluetooth_hci/host/trait.Hci.html">bluetooth_hci::host::Hci</a> extension trait, so they must be imported before they can be used:</p><pre>use bluetooth_hci::host::Hci;</pre><p>For example, to read the chip’s local version information:</p><pre>bnrg.with_spi(&amp;mut spi, |c| {<br>    c.read_local_version_information()<br>});</pre><p>There are various places that you could put one of the nb macros:</p><ul><li>Inside the block</li><li>Outside the with_spi call</li><li>In the calling function</li></ul><p>For more methods with more complex arguments, the crate checks that the values are within spec before making the call. In as many places as possible, the arguments are constructed using the builder pattern so that they cannot be invalid at the time the method is called.</p><p>Consider the <a href="https://docs.rs/bluetooth-hci/0.0.3/bluetooth_hci/host/trait.Hci.html#tymethod.le_set_advertising_parameters">le_set_advertising_parameters</a> call:</p><pre>bnrg.with_spi(&amp;mut spi, |c| {<br>    c.le_set_advertising_parameters(<br>        &amp;bluetooth_hci::host::AdvertisingParameters {<br>            advertising_interval: AdvertisingInterval::for_type(<br>                AdvertisingType::ConnectableUndirected,<br>            ).with_range(<br>                Duration::from_millis(21),<br>                Duration::from_millis(1000),<br>            )?,<br>            own_address_type: OwnAddressType::Public,<br>            peer_address: hci::BdAddrType::Random(hci::BdAddr([<br>                0x01, 0x02, 0x03, 0x04, 0x05, 0x06,<br>            ])),<br>            advertising_channel_map:<br>                Channels::CH_37 | Channels::CH_39, <br>            advertising_filter_policy:<br>                AdvertisingFilterPolicy::AllowConnectionAndScan,<br>        })?<br>);</pre><p>Here we see both potential types of errors. The advertising interval has different requirements based on the advertising type. If these are not met, the <a href="https://docs.rs/bluetooth-hci/0.0.3/bluetooth_hci/host/struct.AdvertisingInterval.html">AdvertisingInterval</a> will not be constructed. The call itself may fail if the advertising channel map is empty. These failures are unrelated to failures from the chip itself. Those are communicated back to the host via either <a href="https://docs.rs/bluetooth-hci/0.0.3/bluetooth_hci/event/struct.CommandStatus.html">CommandStatus</a> or <a href="https://docs.rs/bluetooth-hci/0.0.3/bluetooth_hci/event/command/struct.CommandComplete.html">CommandComplete</a> events. However, the crate is designed so that any malformed commands are not even sent to the controller, but fail at the call site. This cannot catch everything, though. For example, most commands take a connection handle, and only the controller itself can know which handles are valid.</p><h3>Vendor-Specific Commands</h3><p>The BlueNRG defines many commands in addition to the subset of the standard that it supports. These are split into several extension crates, which must be imported individually:</p><pre>use bluenrg::gap::<a href="https://docs.rs/bluenrg/0.0.3/bluenrg/gap/trait.Commands.html">Commands</a> as GapCommands;<br>use bluenrg::gatt::<a href="https://docs.rs/bluenrg/0.0.3/bluenrg/gatt/trait.Commands.html">Commands</a> as GattCommands;<br>use bluenrg::hal::<a href="https://docs.rs/bluenrg/0.0.3/bluenrg/hal/trait.Commands.html">Commands</a> as HalCommands;<br>use bluenrg::l2cap::<a href="https://docs.rs/bluenrg/0.0.3/bluenrg/l2cap/trait.Commands.html">Commands</a> as L2CapCommands;</pre><p>The BlueNRG crate’s API is similar to Bluetooth-HCI. Commands that are known to have invalid parameters are not even sent to the controller, but are rejected at the call site. Other failures are determined by the chip, and returned as CommandStatus or CommandComplete events.</p><p>One potential wrinkle you will find when using both the GAP and GATT commands is that both extensions define an init method. Assuming both traits are imported, they must be distinguished manually, and the controller must be cast appropriately:</p><pre>bnrg.with_spi(&amp;mut spi, |c| {<br>    GattCommands::init(c as &amp;mut GattCommands&lt;Error = _&gt;)?;<br>    GapCommands::init( c as &amp;mut GapCommands&lt;Error = _&gt;,<br>        bluenrg::gap::Role::PERIPHERAL, false, 7, )?;<br>});</pre><h3>Reading from the Controller</h3><p>The Controller trait defines low-level methods to communicate with the controller. These methods operate on the byte level, not the Bluetooth event level, which is not at all convenient. The bluetooth-hci crate defines an extension trait that adds a read method that returns a Bluetooth event:</p><pre>use bluetooth_hci::host::uart::Hci;</pre><p><em>Note: there is another extension trait in </em><a href="https://docs.rs/bluetooth-hci/0.0.3/bluetooth_hci/host/event_link/index.html"><em>host::event_link</em></a><em> that provides a read method, but it would only be useful for a module that does not use a packet type byte as defined in the Bluetooth Spec (version 4.1, Vol 4, Part A, Section 2).</em></p><p>The <a href="https://docs.rs/bluetooth-hci/0.0.3/bluetooth_hci/host/uart/trait.Hci.html#tymethod.read">uart::Hci::read</a> method returns a <a href="https://docs.rs/bluetooth-hci/0.0.3/bluetooth_hci/host/uart/enum.Packet.html">uart::Packet</a>. Currently, the only packet type is an event packet, but other packet types (ACL Data and Sync Data) may be supported in the future.</p><p>read returns a <a href="https://docs.rs/bluetooth-hci/0.0.3/bluetooth_hci/event/enum.Event.html">bluetooth_hci::event::Event</a>, which must be specialized with the particular vendor-specific event type. The Event enum has one value for each supported standard event, and one catch-all value representing a vendor-specific event. The vendor-specific type itself has several associated types that define various extension points:</p><ul><li>Error: errors that may occur when deserializing vendor-specific events (such as out-of-spec values).</li><li>Status: vendor-specific status codes that may be used in CommandStatus or CommandComplete events</li><li>ReturnParameters: payloads for CommandComplete events for vendor-specific commands.</li></ul><h3>Example</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46017732691dc827dde08e98c8982a26/href">https://medium.com/media/46017732691dc827dde08e98c8982a26/href</a></iframe><p>Let’s break this down in smaller chunks:</p><pre>match block!(bnrg.with_spi(&amp;mut spi, |c| c.read())) {<br>    Ok(p) =&gt; {...}<br>    Err(e) =&gt; {...}<br>}</pre><p>This is how we read a Bluetooth event from the controller. Note that we use the <a href="https://docs.rs/nb/0.1.1/nb/macro.block.html">nb::block!</a> macro to ensure we get a complete event (or error out). This could equivalently be written as:</p><pre>bnrg.with_spi(&amp;mut spi, |c| block!(c.read()))</pre><p>which would probably provide better performance, since the loop hidden in the block macro would be inside the closure passed to with_spi, rather than the read loop including the with_spi call.</p><p>In order for the call to read to successfully compile, we must specify the vendor-specific event type. Rust’s powerful type inference comes to our rescue, since we <em>do</em> specify the type on line 9 when we unpack the Vendor event to get a <a href="https://docs.rs/bluenrg/0.0.3/bluenrg/event/enum.BlueNRGEvent.html">BlueNRGEvent</a>.</p><pre>let hci::host::uart::Packet::Event(e) = p;</pre><p>The call to read doesn’t directly return an event. Instead, it returns a Packet, and we need to extract the event from it. In the future, other packet types may be implemented, so this would need to become another match or an if-let.</p><pre>bluetooth_hci::event::Event::ConnectionComplete(params) =&gt; {...}</pre><p>Here we extract the payload of the connection complete event. Now params contains the structure returned by the controller.</p><pre>bluetooth_hci::event::Event::Vendor(<br>    bluenrg::event::BlueNRGEvent::HalInitialized(reason),<br>) =&gt; {...}</pre><p>This is how we extract a particular vendor-specific event. In this case, the BlueNRG sends a HalInitialized event every time it starts up. The <a href="https://docs.rs/bluenrg/0.0.3/bluenrg/event/enum.ResetReason.html">reason</a> indicates why the controller restarted.</p><pre>nb::Error::Other(<br>    bluetooth_hci::event::Error::BadLinkType(t),<br>) =&gt; (),</pre><p>In the error branch of the outer match, we need to handle all of the errors that may occur when reading an event. Recall that read returns an <a href="https://docs.rs/nb/0.1.1/nb/type.Result.html">nb::Result</a>, and all “real” errors will be wrapped in <a href="https://docs.rs/nb/0.1.1/nb/enum.Error.html">nb::Error::Other</a>.</p><p>This line extracts a standard error that can occur when trying to deserialize a connection complete event, which indicates that the controller sent an unknown value as the link type.</p><pre>nb::Error::Other(bluetooth_hci::event::Error::Vendor(<br>    bluenrg::event::BlueNRGError::UnknownResetReason(code),<br>)) =&gt; (),</pre><p>Here we extract a particular vendor-specific error. This particular error occurs when reading the HalInitialized event, and the reason is an undocumented value.</p><pre>nb::Error::WouldBlock =&gt; (),</pre><p>For completeness, the compiler forces us to handle the WouldBlock error, even though we know it can never occur (since we wrap the read in a block! call).</p><h3>Next Steps</h3><p>So what’s next for Bluetooth-HCI and BlueNRG? First, I’m going to actually try <em>using</em> these crates to develop some embedded applications. So, in the immediate future, I’ll be figuring out how the ergonomics and performance of these crates can be improved. Aside from bug fixes though, I don’t foresee any major changes for a while. Once I have some experience with them, I’ll be stabilizing the APIs (at least enough to provide a 0.1.0 series).</p><p>There is still a <em>ton</em> of work to be done to implement the full Bluetooth specification for Bluetooth-HCI. If there’s something in particular that you want to see supported, feel free to raise an issue on <a href="https://github.com/danielgallagher0/bluetooth-hci/issues">Github</a>. (I’ll just be happy someone is using the crate enough to want something fixed!) PRs are always welcome.</p><h3>Ideas for Improvement</h3><p>As I was implementing these crates, I came up with a few ideas that may make them easier to use or more performant. As I mentioned, I’ll be using the current API for a while to see if it would be worth it to implement these changes.</p><h3>Postponing Event Deserialization</h3><p>In the current API, read will attempt to read an event, and will do all error-checking on that event before it is returned to the caller. However, if the caller chooses to ignore certain events, that work is completely wasted. This change would postpone the error checking to the point where particular values are used. So instead of read returning an UnknownResetReason, it would return a HalInitialized event. Then trying to get the reason would return an UnknownResetReason error.</p><h4>Add a Blocking API</h4><p>After we send a command to the controller, we will need to call read to get the CommandStatus or CommandComplete event that the controller sends in response to that command. While this asynchronous API is going to integrate better with a complex application, a blocking API is vastly easier to use.</p><p>If a command currently causes the controller to send a CommandComplete event, the blocking API would wait until the CommandComplete was sent, then return those return parameters to the caller. If a command generates a CommandStatus, the command would wait for that event, then return the status to the caller.</p><p><em>Originally published at </em><a href="https://www.219design.com/bluetooth-low-energy-with-rust/"><em>www.219design.com</em></a><em> on September 27, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4a4fc329d75" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HTS221 Humidity and Temperature Sensor]]></title>
            <link>https://medium.com/@pdanielgallagher/hts221-humidity-and-temperature-sensor-88056ea9e5fa?source=rss-102b97b1e306------2</link>
            <guid isPermaLink="false">https://medium.com/p/88056ea9e5fa</guid>
            <category><![CDATA[embedded]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Daniel Gallagher]]></dc:creator>
            <pubDate>Tue, 20 Mar 2018 04:16:48 GMT</pubDate>
            <atom:updated>2018-03-20T04:16:48.453Z</atom:updated>
            <content:encoded><![CDATA[<h4>Environmental Sensing in Rust</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*6r6y-JOqkPVBq6V4gk65Ww.jpeg" /><figcaption>The HTS221 is a tiny (2x2x0.9mm) MEMS environmental sensor</figcaption></figure><h3>HTS221</h3><p>ST Micro’s <a href="http://www.st.com/en/mems-and-sensors/hts221.html">HTS221</a> is a “capacitive digital sensor for relative humidity and temperature” that can be used over either I²C or SPI. It is factory-calibrated, so there is no end-user calibration to incorporate into your application.</p><p>The <a href="https://crates.io/crates/hts221">driver</a> provides a simple, high-level API to configure the chip once on startup, then read the temperature and humidity. It also provides type-safe access to configuration registers to support more complex applications (such as turning the chip off to save power, or running the integrated heating element to eliminate condensation).</p><h3>Basic Usage</h3><p>To use hts221, you need a implementation of <a href="https://crates.io/crates/embedded-hal">embedded-hal</a>; I’ve been using <a href="https://crates.io/crates/stm32f30x-hal">stm32f30x-hal</a>, though you could use any concrete HAL that provides I²C support (specifically just Write and WriteRead support). There is a Builder that provides an easy way to configure the chip on creation, after which you can read simply the humidity and temperature from the sensor.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/10325f2402ddf67db2660cf3b9deb3e3/href">https://medium.com/media/10325f2402ddf67db2660cf3b9deb3e3/href</a></iframe><p>The relative humidity is reported from the chip at a resolution of 0.5%, and temperature is reported at a resolution of 0.125 °C, which is reflected in the x2 and x8 suffixes, respectively. That is, the results are fixed precision, where the exponent for humidity is -1, and the exponent for temperature is -3. For example, if humidity_x2 returns 97, then the relative humidity is 46.5%. And if temperature_x8 returns 171, then the temperature is 21.375 °C. These resolutions were chosen because they are the resolution of the calibration values that are stored on the chip. While these resolutions are significantly higher than the stated sensitivity of the chip (0.004 rH% and 0.016 °C, respectively), they are well within the stated <em>accuracy</em> (3.5 rH% and 0.5 °C).</p><h3>API</h3><p>The <a href="https://docs.rs/hts221/0.1.0/hts221/">API</a> is split into two modules: the primary module provides a high-level access to the sensor, and the <a href="https://docs.rs/hts221/0.1.0/hts221/device/index.html">device</a> module provides low-level access to the device registers.</p><h4>Sensor-Level API</h4><p>Given an HTS221 value, you can read the relative humidity and temperature using humidity_x2 and temperature_x8. These calls are blocking:</p><pre>// given hts221<br>let rel_humidity = hts221.humidity_x2() / 2;<br>let temperature = hts221.temperature_x8() / 8;</pre><p>You can also access most registers from the HTS221 value.</p><p>To create an HTS221 value, you need to use the <a href="https://docs.rs/hts221/0.1.0/hts221/struct.Builder.html">Builder</a> to set up the chip. The builder handles the low-level details you will need to initialize the chip for simple applications. Once you have an HTS221, you can read the humidity and temperature directly. The builder reads and stores all of the calibration registers, so there is no need to read them after initialization.</p><pre>let hts221 = hts221::Builder::new(i2c)<br>    .with_avg_t(hts221::AvgT::Avg256)<br>    .with_avg_h(hts221::AvgH::Avg512)<br>    .powered_up()  // default<br>    .with_update_mode(hts221::UpdateMode::Block)  // default<br>    .with_data_rate(hts221::DataRate::Continuous1Hz)<br>    .with_data_ready_disabled()  // default<br>    .build()?;</pre><p>The Builder provides an option for every field of every configuration register on the chip.</p><ul><li>Number of temperature samples averaged. The chip will average a number of internal samples to produce one output sample. The more samples averaged, the more power the chip draws. with_avg_t sets this value. If with_avg_t is not called on the builder, this value is unchanged. This register is persistent across power loss. I would recommend setting this explicitly anyway.</li><li>Number of humidity samples averaged. with_avg_h sets this value. Similarly, if this is not called on the Builder, the value is unchanged.</li><li>Power-down. This bit is set by calling powered_up or powered_down on the Builder. By default, the chip is powered on.</li><li>Block data update mode. This bit is set by calling with_update_mode using either UpdateMode::Block or UpdateMode::Continuous. Block mode is the default. The humidity and temperature ADC values are 16-bits, which are stored in 2 separate 8-bit registers each. Block update mode ensures that the chip does not update the high byte after the low byte is read until the high byte is read, so the two bytes are always from the same sample.</li><li>Output data rate. This is set by calling with_data_rate on the builder. It defaults to one-shot mode.</li><li>Boot mode. This is set by calling with_boot or without_boot. Without is the default. Setting this bit resets the internal registers to the factory defaults.</li><li>Heating element. This is not exposed by the Builder.</li><li>One-shot enable. This is not exposed by the Builder.</li><li>Data-ready polarity. This is set by calling with_data_ready_polarity. By default, this value is not changed.</li><li>Data-ready output mode. with_data_ready_mode selects either Open-drain or push-pull mode on the output pin. By default, the value is not changed.</li><li>Data-ready interrupt enable. with_data_ready_enabled enables the external interrupt line (pin 3). with_data_ready_disabled disables it. By default, it is disabled.</li></ul><h4>Register-Level API</h4><p>From an HTS221 object, you can access all of the read-write registers as well as some important read-only registers. Accessing any of the registers performs a blocking read to get the current register value. All of the read-write registers also provide a modify method (similar to a RegisterBlock created by svd2rust) that runs a function (that should modify the register value) then writes the value back to the chip for that register.</p><pre>let cr2 = hts221.cr2()?;<br>cr2.modify(|w| w.set_heater_on())?;</pre><p>Note that the register types are <em>not</em> as type-safe as those created by svd2rust, and that w above is the same type (even the same object) as cr2. So the following will compile, but will not turn the heater on:</p><pre>hts221.cr2()?.set_heater_on()?;</pre><p>You can access registers that are not available from the HTS221 struct in the same way that hts221 does internally, through the structs in the <a href="https://docs.rs/hts221/0.1.0/hts221/device/index.html#structs">device</a> module:</p><pre>let h_out = hts221::device::HumidityOut::new(i2c)?;<br>let adc_value: i16 = h_out.value();</pre><pre>let calibration = hts221::device::Calibration::new(i2c)?;</pre><p>The crate does not provide separate access to the high or low bytes of the humidity or temperature reading, or to any of the calibration registers, all of which are returned as part of the Calibration struct.</p><h3>Future Directions</h3><ul><li>Increase the precision of the returned humidity. Within the operating range, we only have 8 bits of sensitivity on the humidity, though the chip provides up to 16 bits, depending on calibration values. The two examples I have on hand both support about 14 bits of precision. For temperature, the API currently supports 11 bits of precision within the operating range, which is sufficient for the two chips I have on hand, which only actually support about 10 bits of precision, based on their calibration values.</li><li>Add errors for saturation conditions. The driver currently silently clamps readings outside the operating range for both temperature and humidity.</li><li>Add SPI support. embedded-hal has traits that should support both blocking and non-blocking SPI communication. The board that my HTS221 is mounted on has VDD tied to CS, which puts the chip into I²C mode, so I am currently unable to test SPI.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/245/1*cK85DCzo1nEhad61ssY-xQ.png" /></figure><ul><li>Add non-blocking I²C support. This depends on <a href="https://github.com/japaric/embedded-hal/issues/50">support</a> from embedded-hal.</li><li>Resolve the I²C <a href="https://github.com/japaric/embedded-hal/issues/35">bus ownership</a> problem in a way that is compatible with other drivers.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88056ea9e5fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Tale of Two Traits]]></title>
            <link>https://medium.com/@pdanielgallagher/a-tale-of-two-traits-774656af1c4f?source=rss-102b97b1e306------2</link>
            <guid isPermaLink="false">https://medium.com/p/774656af1c4f</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[traits]]></category>
            <dc:creator><![CDATA[Daniel Gallagher]]></dc:creator>
            <pubDate>Sat, 17 Mar 2018 15:16:10 GMT</pubDate>
            <atom:updated>2018-03-22T03:23:20.481Z</atom:updated>
            <content:encoded><![CDATA[<h4>And Their Associated Type [sic]</h4><p>I’ve recently been working on <a href="https://github.com/danielgallagher0/hts221">hts221</a>, a crate that interfaces with the <a href="http://www.st.com/en/mems-and-sensors/hts221.html">ST Micro HTS221</a> humidity and temperature sensor over I²C. Thanks to the <a href="https://github.com/japaric/embedded-hal">embedded-hal</a> crate, this ended up being a relatively straightforward translation of the datasheet into Rust, except for one nagging issue…</p><h4>The Problem</h4><p>embedded-hal defines three traits that can be implemented to communicate over I²C: Read, Write, and WriteRead. The HTS221 only responds to requests, so I only need WriteRead (to get internal registers) and Write (to set internal registers). They are defined like so:</p><pre>pub trait Write {<br>    type Error;</pre><pre>    fn write(&amp;mut self, addr: u8, bytes: &amp;[u8]) -&gt; Result&lt;(), Self::Error&gt;;<br>}</pre><pre>pub trait WriteRead {<br>    type Error;</pre><pre>    fn write_read(&amp;mut self, addr: u8, bytes: &amp;[u8], buffer: &amp;mut [u8]) -&gt; Result&lt;(), Self::Error&gt;;<br>}</pre><p>Nice and simple. One method each and an associated type for the error that may occur. For testing, I’m using <a href="https://github.com/japaric/stm32f30x-hal">stm32f30x-hal</a>, which implements them something like this (greatly simplified):</p><pre>#[derive(Debug)]<br>pub enum Error {<br>    // I2C errors...<br>}</pre><pre>pub struct I2c { ... };</pre><pre>impl Write for I2c {<br>    type Error = Error;</pre><pre>    fn write(&amp;mut self, _addr: u8, _bytes: &amp;[u8]) -&gt; Result&lt;(), Self::Error&gt; {<br>        // Blocking write implementation...<br>    }<br>}</pre><pre>impl WriteRead for I2c{<br>    type Error = Error;</pre><pre>    fn write_read(&amp;mut self, _addr: u8, _bytes: &amp;[u8], _buffer: &amp;mut[u8]) -&gt; Result&lt;(), Self::Error&gt; {<br>        // Blocking write/read implementation...<br>    }<br>}</pre><p>Also nice. Since they are both I²C protocols, they share a common Error type. Makes sense. Anything else <em>wouldn’t </em>make sense.</p><p>Now let’s define our structure so that it can use some I²C implementation, and let’s define a method that will turn the chip on:</p><pre>struct HTS221&lt;I2C&gt; {<br>    i2c: I2C,<br>}</pre><pre>impl&lt;I2C&gt; HTS221 where I2C: Write + WriteRead {<br>    pub fn power_on(&amp;mut self) -&gt; Result&lt;(), I2C::Error&gt; {<br>        let mut reg: [u8; 1] = [0];</pre><pre>        self.i2c.write_read(ADDR, &amp;[SUB_ADDR], &amp;mut reg)?;<br>        reg[0] |= POWER_ON_BIT;<br>        self.i2c.write(ADDR, &amp;[SUB_ADDR, reg[0]])<br>    }<br>}</pre><p>Also nice, if I do say so myself. Let’s see what rustc has to say:</p><pre>error[E0221]: ambiguous associated type `Error` in bounds of `I2C`<br>  --&gt; src/oops.rs:14:54<br>   |<br>14 |     pub fn power_on(&amp;mut self) -&gt; result::Result&lt;(), I2C::Error&gt; {<br>   |                                                      ^^^^^^^^ ambiguous associated type `Error`<br>   | <br>  ::: src/traits.rs:2:5<br>   |<br>2  |     type Error;<br>   |     ----------- ambiguous `Error` from `traits::Write`<br>...<br>8  |     type Error;<br>   |     ----------- ambiguous `Error` from `traits::WriteRead`</pre><p>So the compiler doesn’t know that our I2C type only has one, unambiguous, Error type. <em>We </em>know that I2C only has one error type, right? Well, no, not really. All we require is that I2C implements both Write and WriteRead. But there’s no relationship between Write and WriteRead, so there can’t be a relationship between their associated types, even if, in practice, the error types will always be identical.</p><p>Perhaps we could tell the compiler that such a relationship is required?</p><pre>impl&lt;I2C&gt; HTS221&lt;I2C&gt;<br>where<br>     I2C: Write + WriteRead,<br>     &lt;I2C as Write&gt;::Error = &lt;I2C as WriteRead&gt;::Error {<br>    ...<br>}</pre><p>But that yields the following: error: equality constraints are not yet supported in where clauses (#20041). So go check out the <a href="https://github.com/rust-lang/rust/issues/20041">open issue</a>, which leads to an <a href="https://github.com/rust-lang/rfcs/blob/master/text/0195-associated-items.md#constraining-associated-types">RFC</a> about associated types, which explicitly says that this is not allowed:</p><blockquote>In an IMPL_SEGMENT: &lt;I as Iterator&lt;A = uint&gt;&gt;::next is <em>not</em> allowed.</blockquote><p>(If you happen to be reading this after that issue has been resolved, do try to enforce equality in the associated types first.)</p><h4>The Solution</h4><p>While we can’t add the equality constraint for associated types to the impl, we <em>can </em>add an equality constraint on associated types against one of our generic types. So our HTS221 struct also needs to be generic over its error type:</p><pre>struct HTS221&lt;I2C, E&gt; {<br>    i2c: I2C,<br>}</pre><pre>impl&lt;I2C, E&gt; HTS221&lt;I2C, E&gt;<br>where I2C: Write&lt;Error = E&gt; + WriteRead&lt;Error = E&gt; {<br>    // ...<br>}</pre><p>But if HTS221 doesn’t have any fields that depend on type E, we have an unused type parameter, and we can’t compile. Fortunately, there is a standard mechanism for dealing with unused type parameters: <a href="https://doc.rust-lang.org/std/marker/struct.PhantomData.html">PhantomData</a>!</p><p>So we add a PhantomData&lt;E&gt; field to our struct, and we are good to go:</p><pre>struct HTS221&lt;I2C, E&gt; {<br>    i2c: I2C,<br>    _e: PhantomData&lt;E&gt;,<br>}</pre><p>Now all of our methods can return the unambiguous E as their error type:</p><pre>impl&lt;I2C, E&gt; HTS221&lt;I2C, E&gt;<br>where I2C: Write&lt;Error = E&gt; + WriteRead&lt;Error = E&gt;<br>{<br>    fn power_on(&amp;mut self) -&gt; Result&lt;(), E&gt; {<br>        let mut reg: [u8; 1] = [0];</pre><pre>        self.i2c.write_read(ADDR, &amp;[SUB_ADDR], &amp;mut reg)?;<br>        reg[0] |= POWER_ON_BIT;<br>        self.i2c.write(ADDR, &amp;[SUB_ADDR, reg[0]])<br>    }<br>}</pre><p><em>Note: I discovered this solution several days after I initially published this post, with pointers from the embedded Rust working group (particular thanks to </em><a href="https://github.com/jamwaffles"><em>James Waples</em></a><em> and </em><a href="https://github.com/MrBuddyCasino"><em>Michael Böckling</em></a><em>). The remainder of this post discusses the less elegant ways that I had tried to resolve the problem, and a discussion of my short-lived choice.</em></p><h4>Blind Alley 1: Wrapper Trait</h4><p>Since the available traits don’t exactly match up with our needs, one solution could be to introduce an <a href="https://sourcemaking.com/design_patterns/adapter">Adapter</a> in the form of a new trait that provides a single Error associated type in addition to the methods we need:</p><pre>trait I2C {<br>    type Error;</pre><pre>    fn write(&amp;mut self, addr: u8, bytes: &amp;[u8]) -&gt; Result&lt;(), Self::Error&gt;;<br>    fn write_read(&amp;mut self, addr: u8, bytes: &amp;[u8], buffer: &amp;mut[u8]) -&gt; Result&lt;(), Self::Error&gt;;<br>}</pre><p>We have to replace our Write + WriteRead bound with I2C, but otherwise our HTS221 implementation remains unchanged. However, we can no longer directly use the I2c implementation provided by embedded-hal, since it does not implement our wrapper trait, and we cannot implement an external trait (our I2C) on an external struct (embedded-hal’s specific I2c) in our calling code. So we have to use a <a href="https://doc.rust-lang.org/book/second-edition/ch19-03-advanced-traits.html#the-newtype-pattern-to-implement-external-traits-on-external-types">newtype wrapper</a> and implement our trait:</p><pre>struct I2c(hal::I2c);  // simplified<br>impl hts221::I2C for I2c {<br>    type Error = hal::i2c::Error;<br>    fn write(&amp;mut self, addr: u8, bytes: &amp;[u8]) -&gt; Result&lt;(), Self::Error&gt; {<br>        self.0.write(addr, bytes)<br>    }<br>    fn write_read(&amp;mut self, addr: u8, bytes: &amp;[u8], buffer: &amp;mut[u8] -&gt; Result&lt;(), Self::Error&gt; {<br>        self.0.write_read(addr, bytes, buffer)<br>    }<br>}</pre><p>Rust does have trait “interitance” via <a href="https://doc.rust-lang.org/reference/items/traits.html#supertraits">supertraits</a>, but that’s doesn’t help here.</p><pre>trait I2C : Write + WriteRead {<br>    type Error;<br>}</pre><p>If trait A is bounded by supertrait S, then any type that implements A must also implement S. If we try that here, we still get ambiguous Error errors, since our I2C trait only declares an Error type, which is unavailable when we implement Write or WriteRead. In general, we cannot guarantee that the three error types are the same.</p><h4>Blind Alley 2: Wrapper Error</h4><p>Another solution for this particular problem is to create a <em>new </em>error enum that our methods can return, and convert all Write::Error or WriteRead::Error instances to that. This is typically achieved with an enum (or something like <a href="http://tailhook.github.io/quick-error/quick_error/index.html">quick_error</a>):</p><pre>enum&lt;W: Write, WR: WriteRead&gt; Hts221Error {<br>  WriteError(W::Error),<br>  WriteReadError(WR::Error),<br>}</pre><p>and then implementing From to convert from the original error types to the new error type:</p><pre>impl&lt;W: Write, WR&gt; From&lt;W::Error&gt; for Hts221Error&lt;W, WR&gt; {<br>    fn from(e: Write::Error) -&gt; Hts221Error {<br>        Hts221Error::WriteError(e)<br>    }<br>}</pre><p>and similarly for converting from a WriteRead::Error into Hts221Error. Unfortunately, this conflicts with the built-in definition of From&lt;T&gt; for T:</p><pre>error[E0119]: conflicting implementations of trait `std::convert::From&lt;ewrap::Hts221Error&lt;_, _&gt;&gt;` for type `ewrap::Hts221Error&lt;_, _&gt;`:<br>  --&gt; src/ewrap.rs:34:1<br>   |<br>34 | impl&lt;W: Write, WR&gt; From&lt;W::Error&gt; for Hts221Error&lt;W, WR&gt; {<br>   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^<br>   |<br>   = note: conflicting implementation in crate `core`:<br>           - impl&lt;T&gt; std::convert::From&lt;T&gt; for T;</pre><p>Again, we know that there should be no conflict, but the compiler does not know that. Someone could, for example, implement Write using Hts221Error as its Error type!</p><pre>impl Write for Pathological {<br>    type Error = Hts221Error&lt;OtherWrite, OtherWriteRead&gt;;<br>    ...<br>}</pre><p>If that happened, then our From implementation would indeed interfere with the reflexive definition in the standard library. So we have to explicitly convert from the actual error type to our wrapper type using <a href="https://doc.rust-lang.org/std/result/enum.Result.html#method.map_err">map_err</a>:</p><pre>impl&lt;I2C&gt; HTS221 where I2C: Write + WriteRead {<br>    pub fn power_on(&amp;mut self) -&gt; Result&lt;(), Hts221Error&gt; {<br>        let mut reg: [u8; 1] = [0];</pre><pre>        self.i2c.write_read(ADDR, &amp;[SUB_ADDR], &amp;mut reg).<br>            map_err(|e| Hts221Error::WriteReadError(e))?;<br>        reg[0] |= POWER_ON_BIT;<br>        self.i2c.write(ADDR, &amp;[SUB_ADDR, reg[0]]).<br>            map_err(|e| Hts221Error::WriteError(e))<br>    }<br>}</pre><h4>Blind Alley 3: Split API</h4><p>Another idea is to split the API such that any particular function <em>only </em>calls write or write_read, but never both. As it turns out, the real hts221 crate does this naturally in <em>almost </em>every case. Instead of having a power_on method like in this post, I have a method that reads a register and returns it (which only uses write_read), and another function that modifies the register (which only uses write). The only exception is my builder’s build method, which reads the values of several registers, configures them according to the Builder fields, then commits them back to the chip. So bear that in mind, because this method works much better in my concrete situation than it appears to in this post.</p><p>This split API could be implemented as:</p><pre>impl&lt;I2C&gt; HTS221 where I2C: Write + WriteRead {<br>    pub fn ctrl_reg_2_bits(&amp;mut self) -&gt; Result&lt;u8, &lt;I2C as WriteRead&gt;::Error&gt; {<br>        let mut reg: [u8; 1] = [0];</pre><pre>        self.i2c.write_read(ADDR, &amp;[SUB_ADDR], &amp;mut reg)?;<br>        Ok(reg[0])<br>    }</pre><pre>    pub fn power_on(&amp;mut self, reg: u8) -&gt; Result&lt;(), &lt;I2C as Write&gt;::Error&gt; {<br>        self.i2c.write(ADDR, &amp;[SUB_ADDR, reg | POWER_ON_BIT])<br>    }<br>}</pre><p>While this is simple to implement, is forces our downstream users to unify the errors, which is the same problem we’re trying to solve here. Going high enough up the chain, we can use the struct that implements Write and WriteRead:</p><pre>fn init&lt;I2C: hal::I2c&gt;(hts221: &amp;mut HTS221&lt;I2C&gt;) -&gt; Result&lt;(), i2c::Error&gt; {<br>    let cr2 = hts221.ctrl_reg_2_bits()?;<br>    hts221.power_on(cr2)<br>}</pre><p>Note the distinction between the various I²C labels above:</p><ul><li>I2C is the name for our generic type</li><li>hal::I2c is the name of the structure that implements Write and WriteRead.</li><li>i2c in i2c::Error is the module name in the concrete hal crate</li></ul><h4>Comparison</h4><p>None of these solutions is a clear winner. Adding a wrapper trait and newtype wrapper adds some complexity and conceptual indirection. Adding an error wrapper adds a new type and forces users to unwrap the actual error. I also had to manually implement Debug on the enum, since derive could not work since the enum is generic over the Write and WriteRead traits, <em>not</em> their Error types (which would be derivable). Splitting the API pushes the complexity up to the users of our library.</p><p>So from a maintainability standpoint, there is no clear winner, though splitting the API does not come out looking good.</p><p>I tried using cargo asm to try to determine which of these would be fastest. Unfortunately, my toy example was too simple, and <em>everything</em> was compiled out. For hts221, xargo asm blew up. So no low-level comparison.</p><p>How about code size? Now this one surprised me: solution 1 (wrapper trait and newtype) was the smallest of the solutions, closely followed by the split API. While the newtype and new trait add conceptual indirection, Rust ensures it is a zero-cost abstraction. Adding an error wrapper added about 15 KB to an otherwise identical binary, which, while not substantial (about 5% of the total size), does seem surprisingly large, and is likely due to the implementation of Debug.</p><p>Finally, which seems the most idiomatic? I’m relatively new to Rust, so I’m not really in a position to judge, but:</p><ul><li>The split API is clearly not idiomatic. In my case, I had to split a builder’s build method in two. Yikes.</li><li>Adding an error wrapper is so common that there are crates that make it easier. But in this case, I’m trying to <em>unify</em> two unrelated error types because I know they are actually the same, so wrapping them in an enum just to satisfy the compiler works against my goal. It forces users to extract the actual error, and, in either case, treat the error identically (since the same conditions would cause the error for either operation).</li><li>Adding a newtype is <em>so</em> idiomatic that it’s actually called “newtype” instead of “new type”. Adding a new trait is not quite standard practice, but seem seems similar in spirit to the newtype pattern (newtrait?). The biggest downside is that I can’t use supertraits, so I must re-declare all of the methods that I need.</li></ul><p>For hts221, adding a new trait and requiring users to add a newtype is the best option. There’s no runtime cost since the newtype methods are inlined. The traits I need to implement are very thin (only one method each), so the newtype only has two simple proxy methods to implement, which does not seem like an undue burden. It also seems to be the most idiomatic, and when in Rust, do as the Rustaceans do.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=774656af1c4f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rust on the STMicro Nucleo]]></title>
            <link>https://medium.com/@pdanielgallagher/rust-on-the-stmicro-nucleo-7a66b97be549?source=rss-102b97b1e306------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a66b97be549</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[stm32]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <dc:creator><![CDATA[Daniel Gallagher]]></dc:creator>
            <pubDate>Thu, 01 Mar 2018 05:50:42 GMT</pubDate>
            <atom:updated>2018-03-01T05:50:42.487Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JveTynHqEHPtpXn8IXPJxA.jpeg" /></figure><p>For the embedded portion of my <a href="https://medium.com/@pdanielgallagher/broadening-horizons-beffd6ebcee6">project</a>, I had two decisions to make: which processors and chips to use, and which language to write the firmware in. Since this personal project is about learning new skills, I decided to use Rust instead of C. I opted to use STMicro’s Nucleo boards, since their ecosystem has shields that do all of the things I would like (WiFi, BLE, and environmental sensing), and there was also a great <a href="http://blog.japaric.io/quickstart/">Rust tutorial</a> for a similar board. However, since I’ve never really done any embedded development, I decided to start with the old standby: copying code off the internet!</p><p>Starting with the above-mentioned tutorial, I went through a couple of stages in my hello world, starting with the busy-waiting version of the blinking LED. I followed the guide relatively closely, but decided to use the latest versions of both Rust and the cortex-m-quickstart template project.</p><h3>Building a Device Crate</h3><p>I tried to follow the directions for building a device crate using <a href="https://docs.rs/svd2rust/">svd2rust</a>, which should look something like this:</p><pre><strong>$</strong> cargo new --lib stm32f30x &amp;&amp; cd $_ </pre><pre><strong>$</strong> # Fetch the SVD from the database<br><strong>$</strong> curl -LO <a href="https://github.com/posborne/cmsis-svd/raw/python-0.4/data/STMicro/STM32F30x.svd">https://github.com/posborne/cmsis-svd/raw/python-0.4/data/STMicro/STM32F30x.svd</a><br><strong>$</strong> dos2unix STM32F30x.svd</pre><pre><strong>$</strong> # Patch the SVD for extra type safety<br><strong>$</strong> curl -L https://github.com/japaric/stm32f30x/raw/v0.4.0/STM32F30x.patch | patch -p1<br><strong>$</strong> cargo install svd2rust --vers 0.7.0</pre><pre><strong>$</strong> # Turn the SVD file into a device crate<br><strong>$</strong> svd2rust -i STM32F30x.svd | rustfmt &gt; src/lib.rs</pre><p>Correcting for updated versions, paths, etc., and the fact that there was no patch for the STM32F303xE SVD, my commands ended up looking more like this:</p><pre><strong>$</strong> git clone https://github.com/posborne/cmsis-svd<br><strong>$</strong> cargo new --lib stm32f303xe<br><strong>$</strong> cargo install svd2rust<br><strong>$</strong> cd stm32f303xe<br><strong>$</strong> svd2rust -i ../cmsis-svd/data/STMicro/STM32F303xE.svd | rustfmt --force &gt;src/lib.rs<br><strong>$</strong> cargo install cargo-edit<br><strong>$</strong> cargo add cortex-m bare-metal vcell<br><strong>$</strong> xargo build --target thumbv7em-none-eabihf</pre><p>So far, so good. However, as I was getting my program that <em>used </em>this crate to work, I ran into other issues, such as this bit from the <a href="https://docs.rs/cortex-m-rtfm">cortex-m-rtfm documentation</a>:</p><blockquote>If targeting a Cortex-M7 device with revision r0p1 then you MUST enable the cm7-r0p1 Cargo feature of this crate or the Resource.claim and Resource.claim_mut methods WILL misbehave.</blockquote><p>and, after running into a linker error about missing interrupt handlers, I found this in the <a href="https://docs.rs/svd2rust">svd2rust documentation</a>:</p><blockquote>If the “rt” Cargo feature of the svd2rust generated crate is enabled the crate will populate the part of the vector table that contains the interrupt vectors and provide an <a href="https://docs.rs/svd2rust/0.12.0/svd2rust/macro.interrupt.html">interrupt!</a> macro that can be used to register interrupt handlers.</blockquote><p>The final dependencies in Cargo.toml ended up as:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d282087b90fc628c2d80ad621e342265/href">https://medium.com/media/d282087b90fc628c2d80ad621e342265/href</a></iframe><p>I also ended up adding my own <a href="https://docs.rs/svd2rust/0.12.0/svd2rust/#enumeratedvalues">enumeratedValues</a> to the SVD before finalizing the crate (so there is, in fact, a patch to the SVD now), which you can find on <a href="https://crates.io/crates/stm32f303xe">crates.io</a> or <a href="https://github.com/danielgallagher0/stm32f303xe">github</a>.</p><h3>Busy Wait Blinky</h3><p>Technically, my first attempt was the literal “Hello World” program that prints to the debugger, but you can refer to Jorge Aparicio’s post for that; it worked without any changes. The next bit was copying the LED blinking program that used a busy wait. This program almost worked without changes, but the user LED on the Nucleo is connected to a different pin than it is on the Discovery. To find out which one, you need the <a href="http://www.st.com/content/ccc/resource/technical/document/user_manual/98/2e/fa/4b/e0/82/43/b7/DM00105823.pdf/files/DM00105823.pdf/jcr:content/translations/en.DM00105823.pdf">user manual</a> for the <a href="http://www.st.com/content/st_com/en/products/evaluation-tools/product-evaluation-tools/mcu-eval-tools/stm32-mcu-eval-tools/stm32-mcu-nucleo/nucleo-f303re.html">Nucleo F303RE</a>, which says</p><blockquote><strong>User LD2</strong>: the green LED is a user LED connected to Arduino signal D13 corresponding to STM32 I/O PA5 (pin 21) or PB13 (pin 34) depending on the STM32 target. Refer to Table 11 to Table 23</blockquote><p>Table 14 has the description of the Arduino connectors for the F303RE, which indicates that Arduino signal D13 corresponds to PA5, which is used for SPI1_SCK, with no mention of LD2 or an LED. I ended up trying both PB13 and PA5, and PA5 was the one I wanted.</p><p>In my initial bring-up, I had not yet added enumerated values to my SVD, so I also had to replace some of the calls that used those wrappers with direct, generic, calls that manipulated the bits, such as</p><pre>// In the original:<br>tim7.cr1.write(|w| w.opm().continuous());</pre><pre>// ...became<br>tim7.cr1.write(|w| w.opm().clear_bit());</pre><p>The correspondence between enumerated value and bit value can be found by deciphering the <a href="http://www.st.com/resource/en/reference_manual/dm00043574.pdf">user manual</a> for the <a href="http://www.st.com/en/microcontrollers/stm32f303re.html">processor</a>, which says (on page 678, describing TIM6/TIM7’s CR1 register)</p><blockquote>Bit 3 <strong>OPM</strong>: One-pulse mode<br> 0: Counter is not stopped at update event<br> 1: Counter stops counting at the next update event (clearing the CEN bit).</blockquote><h3>Interrupting Blinky</h3><p>As japaric says at the end of his initial post, this initial blinky program</p><blockquote>is blocking code that forces the processor to uselessly busy wait for a whole second when it could have been doing something more useful.</blockquote><p>His <a href="http://blog.japaric.io/fearless-concurrency/">next post</a> introduces <a href="https://docs.rs/cortex-m-rtfm">cortex-m-rtfm</a>, which uses interrupts to coordinate concurrent tasks. Since I am trying to use the latest and greatest, I ended up having all sorts of issues, as the code from that post wouldn’t work. Eventually I discovered that I was using cortex-m-rtfm v3, which has a much simpler (though very different) API from v1 described in that post. There is a great <a href="http://blog.japaric.io/rtfm-v3/">introduction</a> to v3 by japaric as well, though the <a href="https://docs.rs/cortex-m-rtfm/0.3.1/cortex_m_rtfm/examples/_1_one_task/index.html">one task</a> example that is packaged with the source is exactly an interrupt-based program to blink an LED. Update some pins, and <em>presto-chango</em> we have a working, efficient, blinking LED!</p><p>The factory firmware for the Nucleo-F303RE has a blinking LED, but also lets you cycle between 3 frequencies by pressing the user (blue) push button on the board. This, I think, would be a good exercise to ensure I can go beyond the tutorial blogs. I’m new to embedded development, so I wrote out what I knew I needed:</p><ul><li>Which pin is the user button on?</li><li>Which interrupt gets called when that button is pressed?</li></ul><p>After consulting the manual for the Nucleo, I found that the button is connected to PC13 (i.e., GPIO-C, pin 13), which should trigger external interrupt 13. But wait, there <em>is</em> no external interrupt 13, only an external interrupt 15–10, though that seems a likely candidate.</p><p>So I update my init function to enable GPIOC, and set up my RTFM task for EXTI15_10 to cycle my LED frequency… and my LED is still blinking at 1 Hz.</p><p>After a bit more digging around in the user manual, I find that external interrupt 13 (EXTI13) is not automatically connected to PC13, but can actually be used by pin 13 from <em>any</em> GPIO (though only 1 at a time). To configure EXTI13 to be triggered by PC13, I have to configure EXTI13 using SYSCFG_EXTICR4 (system configuration controller external interrupt configuration register 4), bits 7–4 to be 010, which svd2rust makes relatively straightforward:</p><pre>p.device.SYSCFG.exticr4.modify(|_, w| unsafe {<br>    w.exti13().bits(0b010)<br>});</pre><p>With appropriate use of enumerated values in the SVD, we could eliminate the unsafe block, so it would read</p><pre>p.device.SYSCFG.exticr4.modify(|_, w| w.exti13().pc13());</pre><p>While this doesn’t exactly read like eloquent prose, it does closely match the language in the user manual, which lets the reader look up the documentation for this magic incantation.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FKs7bc35PQ88%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DKs7bc35PQ88&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FKs7bc35PQ88%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/991d58e79ede20254330f1958bc9e3d7/href">https://medium.com/media/991d58e79ede20254330f1958bc9e3d7/href</a></iframe><p>The latest version is available on <a href="https://github.com/danielgallagher0/blinky-nucleo-f303re">github</a>.</p><h3>Onward!</h3><p>If you followed japaric’s “Rust your ARM microcontroller!” post, but found that it doesn’t quite accord with the state of the art, hopefully this post has pointed you in the right direction. I’m well aware this is <em>not</em> a step-by-step guide, but is more of a landmark-oriented description of how I got my embedded Rust project off the ground.</p><p>I’ve barely scratched the surface of both Rust and embedded programming, but the most important lesson I’ve learned so far is: documentation is king. For all things embedded, check the appropriate user manual (mostly for the chip, but some information is particular to the finished board). For Rust, the source code is the ultimate arbiter of truth. Cargo downloads all dependencies and places them in ~/.cargo/registry/src. Your Cargo.lock file has the exact versions you’re compiling against, so you can check the appropriate crate’s source.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a66b97be549" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Selecting a Database]]></title>
            <link>https://medium.com/@pdanielgallagher/selecting-a-database-5bb07654729f?source=rss-102b97b1e306------2</link>
            <guid isPermaLink="false">https://medium.com/p/5bb07654729f</guid>
            <category><![CDATA[mongodb]]></category>
            <dc:creator><![CDATA[Daniel Gallagher]]></dc:creator>
            <pubDate>Mon, 29 Jan 2018 04:48:36 GMT</pubDate>
            <atom:updated>2018-01-29T04:53:02.464Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mx3MUKkPENbaIR-vKGeLDw.jpeg" /><figcaption>Guess what I chose?</figcaption></figure><p>To start on my pet project, I sketched out a couple of pages of ideas, then decided to get right to building <em>something. </em>I’ve done quite a bit of reading over the years about libraries and technologies that I’ve never had a chance to use at work, so I have a decent idea of how I want my eagle’s-eye architecture to look:</p><ul><li>Devices talk to each other</li><li>A “base station” devices talks to a REST server</li><li>Apps and the web server talk to the same REST server</li><li>REST server talks to a database</li></ul><p>I prefer to work iteratively (I hesitate to use the loaded A-word), so my course of action is to get a complete end-to-end system working (for some limited definition of working), and flesh it out as I need to.</p><p>Since this is a one-person project, and I have to start somewhere, I’ll start with the database. I’ve already decided I want to use a NoSQL database. It may or may not be appropriate for a project of this type, but that’s not my concern. My concern is learning something new to me.</p><p>I decided to go with a free cloud-hosted MongoDB database at <a href="https://mlab.com/">mlab</a>. Their “Sandbox” tier is free up to half a gig, which should be more than sufficient for my needs. After creating an account, you have to create a database, which needs a name, tier, hosting service, and location. I don’t really care who hosts this database, so I chose an Azure service, since they have a server near me. Finally, in order to actually access the database, you’ll need to create a database user.</p><p>I also need to install the MongoDB shell so I can test my new database. Technically, if I squint, this isn’t strictly required, since my server process should be able to access my database directly. But I’d much rather confirm that the database works correctly before adding more things that could go wrong.</p><p>So head on over to the <a href="https://docs.mongodb.com/manual/installation/">MongoDB</a> documentation, download and install Mongo locally. Again, I’m going to stick with the community edition, since I don’t need any <a href="https://www.mongodb.com/products/mongodb-enterprise-advanced">enterprise</a> features.</p><p>The MongoLab database page has the exact command necessary to access the database from the mongo shell, as well as the URI to access the database from a driver. I run the shell command, just to verify that I have access.</p><pre>mongo &lt;server&gt;.mlab.com:46867/&lt;dbname&gt; -u &lt;dbuser&gt; -p &lt;dbpassword&gt;</pre><p>I don’t know what tables I’ll need just yet, so I’m happy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5bb07654729f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Broadening Horizons]]></title>
            <link>https://medium.com/@pdanielgallagher/broadening-horizons-beffd6ebcee6?source=rss-102b97b1e306------2</link>
            <guid isPermaLink="false">https://medium.com/p/beffd6ebcee6</guid>
            <dc:creator><![CDATA[Daniel Gallagher]]></dc:creator>
            <pubDate>Sun, 28 Jan 2018 04:49:45 GMT</pubDate>
            <atom:updated>2018-01-28T04:49:45.400Z</atom:updated>
            <content:encoded><![CDATA[<p>I am a professional software developer. My entire career thus far has been built on building “desktop” applications and services to support them. If I had to break it down by language, I’d say 90% C++, 5% C, 2% Scheme, a smattering of other languages (including build scripts), such as bash, awk, one decent-sized Go program, and makefiles, lots of makefiles. I wrote a Perl script once, when one of my bash scripts grew unwieldy. By OS, I’d say 85% POSIX (almost all of which was Linux), 15% Windows.</p><p>What’s missing here? Oh, yes! Mobile, web (front and back-end), and (going the other way) embedded. The backbones of modern technology.</p><p>So I’m embarking on a learning experience. I’ve decided to add to the panoply of ridiculous IoT devices by creating my own device and writing the entire stack of supporting services and user interfaces (mobile and web). I don’t expect to be done any time soon, and, if I’m being honest with myself, I don’t really expect to be done. Not because the problem is too large, but because I’ll have other things to do before this gets “done”.</p><p>With that in mind, I’ve chosen a toy problem domain, though it is a device that I would use. My $10 solution to a $1 problem is… a pair of thermometers. Specifically, a pair of thermometers that alert you when the temperature inside is warmer than the temperature outside (and the temperature outside is warm enough to be comfortable). In the summer in the Bay Area, days are hot, but nights are cool. My house doesn’t have central air conditioning, so it’s a nightly routine to run around turning off window units and opening windows to cool the house down. So it’s not a product I could make a business out of. You won’t hear about my startup netting $80 million in VC funding.</p><p>The purpose of this endeavor is not really even to make the device. It’s for me to expand my horizons, and document the effort, so that other relative newbies might find something useful. I am also going to pick the languages and tools specifically so that I am learning something new every step of the way (which, considering the solution space, shouldn’t be too much of a stretch).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=beffd6ebcee6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>