Untitled

 avatar
unknown
c_cpp
2 years ago
1.1 kB
4
Indexable
#include <PWM.h>

int PIN_1 = 9;  // Timer 1 is 16-bit, use for 1->1KHz
int PIN_2 = 3;  // Timer 2 is 8-bit, use for 2.5KHz

int config_pin(int p, uint32_t frequency, uint8_t duty)
{
  Serial.print("Pin: "); Serial.print(p); Serial.print(" Freq: "); Serial.print(frequency);
  
  uint8_t timer = digitalPinToTimer(p);
  if(timer == TIMER0B) {
    Serial.print(" Timer: 0");
  } else if(timer == TIMER1A || timer == TIMER1B) {
    Serial.println(" Timer: 1");
  } else if (timer == TIMER2B) {
    Serial.println(" Timer: 2");
  } else{
    Serial.println(" Timer: ???");
  }

  if (!SetPinFrequencySafe(p, frequency)) {
    Serial.print("Failed to initialize Pin ");
    Serial.println(p);
    return false;
  }

  pwmWrite(p, duty);
  return true;
}

void setup()
{
 
  Serial.begin(9600);

  while (!Serial) {
      
  }
  
  // Initialize all timers except for 0, which is used for time keeping functions
  InitTimersSafe(); 
  if (!config_pin(PIN_1, 1, 76)) { //1Hz, 300uS
    while (1) delay(1000);
  }
  if (!config_pin(PIN_2, 2500, 127)) { // 2.5KHz, 200uS
    while (1) delay(1000);
  }
}

void loop()
{ 
  delay(30);      
}
Editor is loading...