Pico-Arduino
PicoGPIOFunction.h
1 #include "pico/stdlib.h"
2 #include "hardware/gpio.h"
3 #include "hardware/adc.h"
4 #include "hardware/pwm.h"
5 #include "hardware/clocks.h"
6 
7 #define GPIO_FUNC_ADC 20
8 
32  public:
33  PicoGPIOFunction(int maxPins=40){
34  pinInfo = new uint8_t[maxPins];
35  for (int j=0; j<maxPins;j++){
36  pinInfo[j] = GPIO_FUNC_NULL;
37  }
38  }
39 
40  // defines the actual pin function - only if it is necessary
41  bool setFunction(pin_size_t pinNumber, gpio_function func){
42  bool updated = false;
43  if (pinInfo[pinNumber]!=func){
44  gpio_set_function(pinNumber, func);
45  updated = true;
46  }
47  return updated;
48  }
49 
50  // ADC has a similar functionality but no gpio_function type
51  void setFunctionADC(pin_size_t pinNumber) {
52  // init if necessary
53  initADC();
54 
55  // setup pin for adc
56  if (pinInfo[pinNumber] != GPIO_FUNC_ADC){
57  adc_gpio_init(pinNumber);
58  pinInfo[pinNumber] = GPIO_FUNC_ADC;
59  }
60 
61  // switch adc if necessary
62  int adc = pinNumber - 26;
63  if (current_adc != adc){
64  adc_select_input((id_t)adc);
65  current_adc = adc;
66  }
67  }
68 
69  // calls adc_init() if necessary - returns true if it has been intialized (the first time)
70  bool initADC(){
71  // init if necessary
72  bool result = false;
73  if (adc_init_flag){
74  adc_init();
75  adc_init_flag = true;
76  result = true;
77  }
78  return result;
79  }
80 
81  // reads a pwm value
82  int readPWM(int pinNumber, float scale=100.0){
83  uint slice_num = pwm_gpio_to_slice_num(pinNumber);
84  // Count once for every 100 cycles the PWM B input is high
85  pwm_config cfg = pwm_get_default_config();
86  pwm_config_set_clkdiv_mode(&cfg, PWM_DIV_B_HIGH);
87  pwm_config_set_clkdiv(&cfg, 100);
88  pwm_init(slice_num, &cfg, false);
89  gpio_set_function(pinNumber, GPIO_FUNC_PWM);
90 
91  pwm_set_enabled(slice_num, true);
92  sleep_ms(10);
93  pwm_set_enabled(slice_num, false);
94  float counting_rate = clock_get_hz(clk_sys) / 100;
95  float max_possible_count = counting_rate * 0.01;
96  int result = pwm_get_counter(slice_num) / max_possible_count * scale;
97  return result;
98  }
99 
100 
101  protected:
102  uint8_t* pinInfo;
103  bool adc_init_flag;
104  int current_adc;
105 
106 
107 };
The pico requires that the function of the pin is defined. In Arduino, there is no such concept: so w...
Definition: PicoGPIOFunction.h:31