element14 Community
element14 Community
    Register Log In
  • Site
  • Search
  • Log In Register
  • 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
  • About Us
  • 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
Raspberry Pi Projects
  • Products
  • Raspberry Pi
  • Raspberry Pi Projects
  • More
  • Cancel
Raspberry Pi Projects
Blog Average bulk samples from Data Acquisition Board for Pi Pico with C++ STL
  • Blog
  • Documents
  • Events
  • Polls
  • Members
  • Mentions
  • Sub-Groups
  • Tags
  • More
  • Cancel
  • New
Join Raspberry Pi Projects to participate - click to join for free!
  • Share
  • More
  • Cancel
Group Actions
  • Group RSS
  • More
  • Cancel
Engagement
  • Author Author: Jan Cumps
  • Date Created: 12 Dec 2023 1:59 PM Date Created
  • Views 1166 views
  • Likes 5 likes
  • Comments 6 comments
  • ADC (Analog-to-Digital Converter)
  • pico
  • data acquisition
  • stl
  • ads1115
  • rp2040
  • daq
  • pico-eurocard
  • raspberry_pi_projects
  • adc
  • test&measurement
Related
Recommended

Average bulk samples from Data Acquisition Board for Pi Pico with C++ STL

Jan Cumps
Jan Cumps
12 Dec 2023
Average bulk samples from Data Acquisition Board for Pi Pico with C++ STL

 shabaz designed a Data Acquisition Board for Pi Pico . In the previous post, I used it in continuous sample mode. I took 1 second worth of samples, in 860 samples per second mode.

In this post, I average those samples; using C++ STL constructs. I'm using all the code from the 1st post, to collect 860 samples in a buffer.

image

Actions to do on that buffer:

  • swap the bytes. The ADS1115 delivers them in the wrong order for Pico math.
  • sum the data in the array, and divide it by array size

In the original program, the buffer is a plain C array, not an STL container. I don't change that. I use STL iterators that can work on such a continuous buffer.

Swapping bytes with a Lambda function

A Lambda function is a small anonymous set of instructions, that (in this case) will apply on all values of a dataset. The Lambda in my code swaps bytes in an uint16_t:

{ u = u >> 8 | u << 8; }

Here is how STL can perform this on all elements of my 860 samples buffer:

std::for_each(std::begin(buf), std::end(buf), [](uint16_t& u){ u = u >> 8 | u << 8; }); // swap bytes

The std::begin() and std::end() iterators work on a common buffer. std::for_each() will iterate from begin to end, and call the Lambda on each element in that range. Result is that the buffer is modified in place, with bytes swapped for each uint16_t value in that buffer.

Calculate the average with a numeric algorithm

In this case, the sum of the buffer is taken. Then it's divided by the sum of elements in the buffer. Again, I'm using STL iterators to traverse the buffer. In this case, the buffer itself does not change state.

std::accumulate sums up all elements in the given range:

double sum = std::accumulate(std::begin(buf), std::end(buf), 0.0);

Then the average is taken. the std::size() STL function works on a plain C buffer.

uint16_t avg = sum / std::size(buf);

This could be done in a single call. The result of std::accumulate() is a variable of type auto. Both swapping and accumulation could be written like this:

// for averaging
#include <iterator>
#include <numeric>

uint16_t buf[SAMPLES];

std::for_each(std::begin(buf), std::end(buf), [](uint16_t& u){ u = u >> 8 | u << 8; }); // swap bytes
uint16_t avg = std::accumulate(std::begin(buf), std::end(buf), 0.0) / std::size(buf);

printf("AVG = %.3f V\n", to_volts(BOARD0, 0, avg));

Full source of the main function. There are more functions that can be STL'd (the to_volts() conversion, printing the results, ...). For this post, I wanted to focus on the two calls related to averaging.

// ************ main function *******************
int main(void) {

    stdio_init_all();

    board_init();

    build_data_rate(BOARD0, DR_860);
    build_gain(BOARD0, AIN1, GAIN_2_048); // +- 2.048V

    #define SAMPLES 860
//    #define SAMPLES 10

    uint16_t buf[SAMPLES];
    
    build_cont_conversion(0);
    adc_set_mux(BOARD0,0,false);
    adc_enable_rdy(0);

    uint8_t* buf8_ptr = (uint8_t*)buf;
    *buf8_ptr = ADS1115_REG_CONVERSION;
    i2c_write_blocking(i2c_port, adc_addr[BOARD0], buf8_ptr, 1, false);

    uint8_t* buf8_end_ptr = ((uint8_t*)buf) + (sizeof buf);
    rdy = false;

    while (buf8_ptr < buf8_end_ptr) {
        if (rdy) {
            rdy = false;
            i2c_read_blocking(i2c_port, adc_addr[BOARD0], buf8_ptr, 2, false);
            buf8_ptr += 2;
        }
    }

    uint16_t* buf16_ptr = buf;
    uint16_t* buf16_end_ptr = buf + (sizeof buf) / 2;

    // buffer bytes will now swapped, 
    // and that's needed for the next actions
    // use stl iterator and lambda function
    std::for_each(std::begin(buf), std::end(buf), [](uint16_t& u){ u = u >> 8 | u << 8; }); // swap bytes

    // prereq: bytes are already swapped
    double sum = std::accumulate(std::begin(buf), std::end(buf), 0.0);
    uint16_t avg = sum / std::size(buf);
    printf("AVG = %.3f V\n", to_volts(BOARD0, 0, avg));

    while (buf16_ptr < buf16_end_ptr) {
        // *buf16_ptr = *buf16_ptr >> 8 | *buf16_ptr << 8; // swap bytes already done with stl lambda
        printf("AIN1 = %.3f V\n", to_volts(BOARD0, 0, *buf16_ptr));
        buf16_ptr++;
    }

    while (FOREVER) {}
}

Check the previous post for the source of the functions called in this example.

image

The use of the iterators, Lambda function and other STL functions did not add noticeable resource use.
I also tried to use streaming to cout. It works, but that's a Flash hog. The internet has multiple reports on the big size of the IOStream library for an embedded device, and my tests confirm that.

Enjoy.

  • Sign in to reply
  • Jan Cumps
    Jan Cumps over 1 year ago

    Create an array of voltages (double) from an array of samples (uint16_t):

        // convert every value to voltage
        double volts[SAMPLES];
        std::transform(std::begin(buf), std::end(buf), std::begin(volts),
            [](uint16_t u){ return to_volts(BOARD0, 0, u); });
    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • More
    • Cancel
  • DAB
    DAB over 1 year ago

    Nice update Jan.

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • More
    • Cancel
  • Jan Cumps
    Jan Cumps over 1 year ago in reply to Jan Cumps

    correction: I checked. It's the IOStream lib

    Using the iterators, the accumulate algorithm, the Lambda, and for_each didn't add anything meaningful vs using plain C loops.

    Using the IOStream (cout << ...) adds 620 Kb in release build mode.

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • More
    • Cancel
  • Jan Cumps
    Jan Cumps over 1 year ago in reply to shabaz

    I tried to use it lightweight in this example. Evaluate its capabilities to work on a typical buffer of sensor readings.

    That's why I tried two scenarios:

    • a modifying action, where all values of the buffer range are changed
    • a non-modifying action, where all values are summed

    Both use an iterator wrapper std::begin() and std::end(). In this case, this mechanism reduces at compile time into a for (0 < len; ++) type of loop.

    No reason to be naive though - the .uf2 file grew from 75K to 740K. I haven't checked full resource report or try to find out what the main contender is (the STL? IOStream?)

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • More
    • Cancel
  • shabaz
    shabaz over 1 year ago

    Hi Jan,

    Very neat, STL is an elegant problem-solver. I've not used std::accumulate before (I'm familiar with a subset of STL, and I recall what a complete mystery it was at the start of learning C++!

    • 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