• Welcome to Andy's Workshop Forums. Please login or sign up.
 
March 29, 2024, 06:15:16 am

News:

SMF - Just Installed!


stm32plus code snippets

Started by Andy Brown, July 26, 2015, 10:35:54 am

Previous topic - Next topic

Andy Brown

As I write more and more stm32plus code I thought it might help people if I share small snippets of code to do common tasks in the spirit of the github gist. Feel free to contribute snippets yourself and/or comment on others.
It's worse than that, it's physics Jim!

Andy Brown

I needed to generate a high frequency 50/50 PWM signal out of PA2 on the F0. The device I was working with was fairly flexible on the exact frequency so I chose 12MHz because it's an exact division of the 48MHz core clock which means that a precise frequency will be generated. PA2 is the TIM2 channel 3 output. Here's how I did it:


Timer2<
        Timer2InternalClockFeature,
        TimerChannel3Feature<>,
        Timer2GpioFeature<
          TIMER_REMAP_NONE,
          TIM2_CH3_OUT
        >
      > clk;

  clk.setTimeBaseByFrequency(24000000,1);
  clk.initCompareForPwmOutput();
  clk.enablePeripheral();
  clk.setDutyCycle(50);


The timer is set to tick at 24MHz with a very low reload count of 1 so it will toggle every tick giving a frequency of 12MHz. Adjusting the frequency will get you different frequencies. For example, 48000000 will get you the maximum frequency of 24MHz and 12000000 gets you 6MHz.
It's worse than that, it's physics Jim!

Andy Brown

A request came in to the github issues tracker asking for an iterator feature for GPIO pins that could function like an STL iterator and therefore take advantage of the utilities provided in the <algorithm> header.

I've now added this feature to the master branch to be released with version 4.0.3. You will need to include <algorithm> for most of the STL algorithms and "util/StdExt.h" for the algorithms that I've imported from the C++11 release of the STL (all_of, any_of, none_of, find_if_not).

Here's some examples of possible usage:

Set all pins high in a group using just the iterator:


GpioC<DefaultDigitalOutputFeature<1,7,9,12,14>> pc;

for(auto it=pc.begin();it!=pc.end();it++) {
  it->set();
}


Set all pins high in a group using a C++11 lambda:


GpioC<DefaultDigitalOutputFeature<1,7,9,12,14>> pc;

std::for_each(pc.begin(),pc.end(),[](GpioPinRef &g) { g.set(); });


Check if all pins are high in a group using a C++11 lambda:


GpioC<DefaultDigitalInputFeature<0,1,2,7,12>> pc;

if(std::all_of(pc.begin(),pc.end(),[](GpioPinRef& g){ return g.read(); }) ) {
  // all pins are high
}


In a configuration where some port pins are output and some are input, do something if at least one of the input pins is set:


GpioC<DefaultDigitalInputFeature<1,7>,DefaultDigitalOutputFeature<8,9>> pc;

if(std::any_of(pc.begin(),pc.end(),[](GpioPinRef& g){ return g.getMode()==Gpio::INPUT && g.read(); }) ) {
  // at least one pin is set
}

It's worse than that, it's physics Jim!