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
70  void initADC(){
71  // init if necessary
72  if (adc_init_flag){
73  adc_init();
74  adc_init_flag = true;
75  }
76  }
77 
78  // reads a pwm value
79  int readPWM(int pinNumber, float scale=100.0){
80  uint slice_num = pwm_gpio_to_slice_num(pinNumber);
81  // Count once for every 100 cycles the PWM B input is high
82  pwm_config cfg = pwm_get_default_config();
83  pwm_config_set_clkdiv_mode(&cfg, PWM_DIV_B_HIGH);
84  pwm_config_set_clkdiv(&cfg, 100);
85  pwm_init(slice_num, &cfg, false);
86  gpio_set_function(pinNumber, GPIO_FUNC_PWM);
87 
88  pwm_set_enabled(slice_num, true);
89  sleep_ms(10);
90  pwm_set_enabled(slice_num, false);
91  float counting_rate = clock_get_hz(clk_sys) / 100;
92  float max_possible_count = counting_rate * 0.01;
93  int result = pwm_get_counter(slice_num) / max_possible_count * scale;
94  return result;
95  }
96 
97 
98  protected:
99  uint8_t* pinInfo;
100  bool adc_init_flag;
101  int current_adc;
102 
103 
104 };
The pico requires that the function of the pin is defined. In Arduino, there is no such concept: so w...
Definition: PicoGPIOFunction.h:31