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