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