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