Pico-Arduino
PicoPIOManager.h
1 
2 #pragma once
3 
4 #include "pico/stdlib.h"
5 #include "hardware/pio.h"
6 #include "hardware/clocks.h"
7 
15 class PIOManager {
16  public:
17  PIOManager(){
18  }
19  ~PIOManager(){
20  stop();
21  }
22 
23  PIOManager pin(int pin){
24  this->pin = pin;
25  return *this;
26  }
27  PIOManager program(pio_program_t program){
28  this->program = program;
29  return *this;
30  }
31  PIOManager config(pio_sm_config config){
32  this->config = config;
33  return *this;
34  }
35  PIOManager pio(PIO pio){
36  this->pio = pio;
37  return *this;
38  }
39 
40  PIOManager &begin(){
41  // to remember this location!
42  uint offset = pio_add_program(pio, &program);
43 
44  // Find a free state machine on our chosen PIO (erroring if there are
45  // none). Configure it to run our program, and start it, using the
46  // helper function we included in our .pio file.
47  state_machine = pio_claim_unused_sm(pio, true);
48 
49  // Map the state machine's OUT pin group to one pin, namely the `pin`
50  // parameter to this function.
51  sm_config_set_out_pins(&config, pin, 1);
52 
53  // Set this pin's GPIO function (connect PIO to the pad)
54  pio_gpio_init(pio, pin);
55 
56  // Set the pin direction to output at the PIO
57  sm_config_set_sideset_pins(&config, pin);
58 
59  // Load our configuration, and jump to the start of the program
60  pio_sm_init(pio, state_machine, offset, &config);
61  return *this;
62  }
63 
64  PIOManager &setup(uint64_t hz, int pin, pio_program_t program, pio_sm_config config, PIO pio = pio0 ){
65  setup(pin, program, config, pio);
66  // defines the speed
67  setFrequency(hz);
68  return *this;
69  }
70 
71  PIOManager setFrequency(uint64_t hz){
72  if (hz>0){
73  float div = clock_get_hz(clk_sys) / hz);
74  sm_config_set_clkdiv(&config, div);
75  pio_sm_set_enabled(pio, state_machine, true);
76  } else {
77  pio_sm_set_enabled(pio, state_machine, false);
78  }
79  return *this;
80  }
81 
82  PIOManager &start() {
83  pio_sm_set_enabled(pio, state_machine, true);
84  return *this;
85  }
86 
87  PIOManager &stop() {
88  pio_sm_set_enabled(pio, state_machine, false);
89  return *this;
90  }
91 
92  protected:
93  PIO pio = pio0;
94  pio_sm_config config;
95  pio_program_t program;
96  uint state_machine;
97  int pin;
98 };
The PIO subsystem on RP2040 allows you to write small, simple programs for what are called PIO state ...
Definition: PicoPIOManager.h:15