element14 Community
element14 Community
    Register Log In
  • Site
  • Search
  • Log In Register
  • About Us
  • Community Hub
    Community Hub
    • What's New on element14
    • Feedback and Support
    • Benefits of Membership
    • Personal Blogs
    • Members Area
    • Achievement Levels
  • Learn
    Learn
    • Ask an Expert
    • eBooks
    • element14 presents
    • Learning Center
    • Tech Spotlight
    • STEM Academy
    • Webinars, Training and Events
    • Learning Groups
  • Technologies
    Technologies
    • 3D Printing
    • FPGA
    • Industrial Automation
    • Internet of Things
    • Power & Energy
    • Sensors
    • Technology Groups
  • Challenges & Projects
    Challenges & Projects
    • Design Challenges
    • element14 presents Projects
    • Project14
    • Arduino Projects
    • Raspberry Pi Projects
    • Project Groups
  • Products
    Products
    • Arduino
    • Avnet Boards Community
    • Dev Tools
    • Manufacturers
    • Multicomp Pro
    • Product Groups
    • Raspberry Pi
    • RoadTests & Reviews
  • Store
    Store
    • Visit Your Store
    • Choose another store...
      • Europe
      •  Austria (German)
      •  Belgium (Dutch, French)
      •  Bulgaria (Bulgarian)
      •  Czech Republic (Czech)
      •  Denmark (Danish)
      •  Estonia (Estonian)
      •  Finland (Finnish)
      •  France (French)
      •  Germany (German)
      •  Hungary (Hungarian)
      •  Ireland
      •  Israel
      •  Italy (Italian)
      •  Latvia (Latvian)
      •  
      •  Lithuania (Lithuanian)
      •  Netherlands (Dutch)
      •  Norway (Norwegian)
      •  Poland (Polish)
      •  Portugal (Portuguese)
      •  Romania (Romanian)
      •  Russia (Russian)
      •  Slovakia (Slovak)
      •  Slovenia (Slovenian)
      •  Spain (Spanish)
      •  Sweden (Swedish)
      •  Switzerland(German, French)
      •  Turkey (Turkish)
      •  United Kingdom
      • Asia Pacific
      •  Australia
      •  China
      •  Hong Kong
      •  India
      •  Korea (Korean)
      •  Malaysia
      •  New Zealand
      •  Philippines
      •  Singapore
      •  Taiwan
      •  Thailand (Thai)
      • Americas
      •  Brazil (Portuguese)
      •  Canada
      •  Mexico (Spanish)
      •  United States
      Can't find the country/region you're looking for? Visit our export site or find a local distributor.
  • Translate
  • Profile
  • Settings
Code Exchange
  • Technologies
  • More
Code Exchange
Blog embedded C++: add cheap bitwise conversion to a register structure
  • Blog
  • Forum
  • Documents
  • Events
  • Polls
  • Files
  • Members
  • Mentions
  • Sub-Groups
  • Tags
  • More
  • Cancel
  • New
Join Code Exchange to participate - click to join for free!
  • Share
  • More
  • Cancel
Group Actions
  • Group RSS
  • More
  • Cancel
Engagement
  • Author Author: Jan Cumps
  • Date Created: 30 Mar 2025 6:20 PM Date Created
  • Views 840 views
  • Likes 6 likes
  • Comments 12 comments
Related
Recommended

embedded C++: add cheap bitwise conversion to a register structure

Jan Cumps
Jan Cumps
30 Mar 2025

This blog is based on real world work. I'm controlling a TI DRV8711 stepper motor controller via SPI.

I need to modify 16-bit registers of that IC. TI provided a header file with register definitions, and code to convert that struct to a 16 bit unsigned integer. That integer can then be sent over SPI.

C code

register struct (TI example: the control register)

 // CTRL Register
 struct CTRL_Register
 {
     uint16_t Address;	// bits 14-12
     uint16_t DTIME;		// bits 11-10
     uint16_t ISGAIN;	// bits 9-8
     uint16_t EXSTALL;	// bit 7
     uint16_t MODE;		// bits 6-3
     uint16_t RSTEP;		// bit 2
     uint16_t RDIR;		// bit 1
     uint16_t ENBL;		// bit 0
 };

code to convert an instance of the struct (reg) to a 16 bit unsigned int and write to SPI:

    uint16_t data;
    // prepare CTRL Register
    data = (reg.Address << 12) | (reg.DTIME << 10) | (reg.ISGAIN << 8) |(reg.EXSTALL << 7) | (reg.MODE << 3) | (reg.RSTEP << 2) | (reg.RDIR << 1) | (reg.ENBL);
    spi_write(data);    

C++ code

in C++, we can teach the structure to convert itself to a 16 bit unsigned int (the operator uint16_t() below): 
I also encapsulated the address of the register. It's fixed, so your firmware should not have to deal with that.

 // CTRL Register
 struct CTRL_Register
 {
     uint16_t DTIME;		// bits 11-10
     uint16_t ISGAIN;	// bits 9-8
     uint16_t EXSTALL;	// bit 7
     uint16_t MODE;		// bits 6-3
     uint16_t RSTEP;		// bit 2
     uint16_t RDIR;		// bit 1
     uint16_t ENBL;		// bit 0
     inline operator uint16_t() const {
        return (0x0000 << 12) | (DTIME << 10) | (ISGAIN << 8) |(EXSTALL << 7) | (MODE << 3) | (RSTEP << 2) | (RDIR << 1) | (ENBL);
     }
 };

and then write the struct directly to SPI (conversion is done by the struct when being passed to this call - because we trained it how to do that).

    spi_write(reg);

Note that there is no conversion in your user code - the struct will do it. We can just pass the struct to the SPI write procedure.
All knowledge on what fields are available in the register, and how to club it into the 16 bits, is contained within the struct.

The code does not add anything to the runtime / firmware. But the register's bit structure knowledge is fully contained within the struct. Your client software doesn't need to shift bits.

Thank you for reading. Critique is welcome.

bonus pub quiz question: why did I put const in the conversion function's declaration?

  • Sign in to reply
  • Jan Cumps
    Jan Cumps 5 months ago

    I reused this for a stepper motor design that I'm developing. But I used the constructor this time, to do the conversion.

    /*  Stepper motor command wrapper
        lightweight 
    */
    class command {
    public:
        inline command(uint32_t steps, bool reverse) : cmd_(steps << 1 | (reverse ? 0 : 1)) {}
        inline operator uint32_t() const { return cmd_; }
    private:
        uint32_t cmd_;
    };

    My stepper motor driver uses 32 bit instructions. 
    Bit 0 is the direction (left/right)
    Bit 31 - 1 are the number of steps.

    During construction, the two parameters are immediately converted to a single uint32_t, ready for the stepper driver.

    How much space does this object take?

    data size (each object): same as an uint32_t
    code size (one time) - and also the cost of a single conversion: same as a call to steps << 1 | (reverse ? 0 : 1);

    example:

    command cmd(steps, reverse);

    At runtime (firmware), this uses exactly the same resources as when you'd use a uint32_t variable, and fill it by calling:

    uint32_t cmd =  steps << 1 | (reverse ? 0 : 1)

    The original post uses late conversion. Data is converted when the operator is called. In that design, The operator uint32_t() has the conversion logic.
    It makes sense. because the developer may want to manipulate individual register parts, before writing.. And we're not expecting arrays of registers.

    In the example that I use in this comment, we don't expect manipulation on the data once it's created. You collect steps and  directions, then send it to the stepper motor.
    In that case, it makes sense to convert to the smallest data size immediately, in the constructor, taking the conversion hit at declaration.
    When the operator uint32_t() is called, it just passes the data.

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • More
    • Cancel
  • Jan Cumps
    Jan Cumps 5 months ago

    The approach allowed me to restrict the code in my firmware to just this:

    image

    At the same time, I used way less clock ticks and other resources (init time, memory) than TI's example. Without adding any costs to their (good, I think, but aged) code.

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • More
    • Cancel
  • Jan Cumps
    Jan Cumps 5 months ago in reply to michaelkellett

    In my C++ posts, I try to distinguish between generic development content, and µController scale topics.

    When I put "embedded" in the subject, I think that the technique is usable in a controller with resources comparable to the smallest ARM family. Most of them also with the tiny ATMEL range - although modern toolchain support is more limiting than the controller's resources in this case.

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • More
    • Cancel
  • michaelkellett
    michaelkellett 5 months ago in reply to Jan Cumps

    Thanks for all that Jan, I'm mega busy the next few days but I should get  a chance to play with it at the end of the week.

    I don't use C++ but my usual tools can compile it so I'll do some comparisons when I get  a chance.

    MK

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • More
    • Cancel
  • Jan Cumps
    Jan Cumps 5 months ago in reply to Jan Cumps

    if you like to experiment with this, here is the  C version (TI's code):

    #include <stdint.h>
    struct CTRL_Register {
        uint16_t DTIME;     // bits 11-10
        uint16_t ISGAIN;    // bits 9-8
        uint16_t EXSTALL;   // bit 7
        uint16_t MODE;      // bits 6-3
        uint16_t RSTEP;     // bit 2
        uint16_t RDIR;      // bit 1
        uint16_t ENBL;      // bit 0
    };

    CTRL_Register reg;

    int main() {
        uint16_t data;
        data = (0x0000 << 12) | (reg.DTIME << 10) | (reg.ISGAIN << 8) |(reg.EXSTALL << 7) | (reg.MODE << 3) | (reg.RSTEP << 2) | (reg.RDIR << 1) | (reg.ENBL);
        return (int)data;
    }
    and C++
    #include <cstdint>
    struct CTRL_Register {
        uint16_t DTIME;     // bits 11-10
        uint16_t ISGAIN;    // bits 9-8
        uint16_t EXSTALL;   // bit 7
        uint16_t MODE;      // bits 6-3
        uint16_t RSTEP;     // bit 2
        uint16_t RDIR;      // bit 1
        uint16_t ENBL;      // bit 0
        inline operator uint16_t() const {
           return (0x0000 << 12) | (DTIME << 10) | (ISGAIN << 8) |(EXSTALL << 7) | (MODE << 3) | (RSTEP << 2) | (RDIR << 1) | (ENBL);
        }
    };

    CTRL_Register reg;

    int main() {
        uint16_t data;
        data = reg;
        return (int)data;
    }
    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • More
    • Cancel
>
element14 Community

element14 is the first online community specifically for engineers. Connect with your peers and get expert answers to your questions.

  • Members
  • Learn
  • Technologies
  • Challenges & Projects
  • Products
  • Store
  • About Us
  • Feedback & Support
  • FAQs
  • Terms of Use
  • Privacy Policy
  • Legal and Copyright Notices
  • Sitemap
  • Cookies

An Avnet Company © 2025 Premier Farnell Limited. All Rights Reserved.

Premier Farnell Ltd, registered in England and Wales (no 00876412), registered office: Farnell House, Forge Lane, Leeds LS12 2NE.

ICP 备案号 10220084.

Follow element14

  • X
  • Facebook
  • linkedin
  • YouTube