I am quite enthusiastic about the new Raspberry Pico. However I find the C SDK not very friendly and I prefer to have something as simple as the Arduino API. I did not want to wait for the official Arduino support – so I started my own project.

PWM in the Pico

I was struggling quite a bit to have PWM working properly and the Pico PWM API is pretty nasty because you have to deal with

  • clock frequencies and frequency dividers
  • counters and wraps
  • interrupts
  • channels and slices

Finally I think I have got it now. I decided to provide a nice high level API for PWM which can support any type of application because you can define the frequency yourself.

Pico PWM reading logic

It took me quite a while to grok the reading logic. I have implemented it in the following way:

  • The API provides the pwm_get_counter() method which can count the number of high cycles. The counting high logic can be defined by calling the pwm_config_set_clkdiv_mode(&config, PWM_DIV_B_HIGH) method.
  • With the help of the interrupt we can determine the counter overflow
  • With the above we can measure the total high cycles during a predefined measuring time period
  • I am repeating the measurement n times in order to calculate the average
  • With the help of the clock_get_hz(clk_sys) method we can calculate the total cycles during the measuring time period. I am not using any clock divider, so the system is counting at the highest resolution.
  • Finally we can just calculate the duty cycle (rate) by dividing: counted high cycles / total cycles!

If you want to study my source code: this functionality is provided by the PicoPWMReader class.

PWM in the Arduino

My simple API is then just used to provide the implementation for the standard Arduino, so that you can just call

The Arduino PWM frequency is usually around 490 Hz. This is good enough to drive some LED but not suited for Servos or Motors.

On top I also provide a Pico compatible Servo class which can be used to drive Servos.

Examples

Here are the links to the examples:

As a conclusion: I have pretty much the full Arduino functionality working now. The only outstanding topic is I2S and taking into consideration the lacking maturity of the standard Pico Framework support for I2S – I am not sure if I want to pick this up myself….

Categories: ArduinoPico

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *