Arduino Uno Q, very poor PWM

@KurtE - @ptillisch

Since you know I can not leave well enough alone, I made it a little more generic - new analogWriteFreq function:

//-----------------------------------------------------------------------------
// Copy of the Arduino Zephyr analog code - to map from Pin Number to zephyr
// object and channel
//-----------------------------------------------------------------------------
#include "wiring_private.h"
#define PWM_PIN 2
#define PWM_DT_SPEC(n, p, i) PWM_DT_SPEC_GET_BY_IDX(n, i),
#define PWM_PINS(n, p, i) \
  DIGITAL_PIN_GPIOS_FIND_PIN(DT_REG_ADDR(DT_PHANDLE_BY_IDX(DT_PATH(zephyr_user), p, i)), \
                             DT_PHA_BY_IDX(DT_PATH(zephyr_user), p, i, pin)),


const struct pwm_dt_spec arduino_pwm[] = {
  DT_FOREACH_PROP_ELEM(DT_PATH(zephyr_user), pwms, PWM_DT_SPEC)
};

/* pwm-pins node provides a mapping digital pin numbers to pwm channels */
const pin_size_t arduino_pwm_pins[] = {
  DT_FOREACH_PROP_ELEM(DT_PATH(zephyr_user), pwm_pin_gpios, PWM_PINS)
};

size_t pwm_pin_index(pin_size_t pinNumber) {
  for (size_t i = 0; i < ARRAY_SIZE(arduino_pwm_pins); i++) {
    if (arduino_pwm_pins[i] == pinNumber) {
      return i;
    }
  }
  return (size_t)-1;
}

void setup() {
  Serial.begin(115200);
delay(2000);
  // Start of the PWM...
  pinMode(PWM_PIN, OUTPUT);
  analogWrite(PWM_PIN, 64);
  delay(100);
  analogWriteFrequency(PWM_PIN, 4000, 50);
  }

void loop() {
}

void analogWriteFrequency(int pin, float freq, float duty)
{
  //Step 1. calculate period
  float T = 1.0/freq;
  //Step 2 convert to nanoseconds
  int Tns = (int)(T * 1000000000.0);
  Serial.println(Tns);
  //Step 3. Calculate Pulse width
  int PW = (int) ((duty / 100.0) * Tns);
  Serial.println(PW);

  // Quick and dirty to set the period and pulse in nano seconds
  size_t idx = pwm_pin_index(pin);
  pwm_set(arduino_pwm[idx].dev, arduino_pwm[idx].channel, Tns, PW, PWM_POLARITY_NORMAL);
}