diff --git a/code/parasite/lib/parasite/pwm.cpp b/code/parasite/lib/parasite/pwm.cpp index 2ae453f..6aaf11e 100644 --- a/code/parasite/lib/parasite/pwm.cpp +++ b/code/parasite/lib/parasite/pwm.cpp @@ -14,20 +14,21 @@ namespace { // No scaling. The PWM counter will increase with a frequency of 16MHz. constexpr unsigned long kPWMFrequencyPrescale = PWM_PRESCALER_PRESCALER_DIV_1; -// In conjunction with the PWM clock frequency, kPWMMaxCounter defines the -// frequency of the square wave. -constexpr int kPWMMaxCounter = 32; -// Since we want a duty cycle of 0.5, we flip the PVM output when the counter -// reaches kPWMMaxCounter / 2/; -constexpr int kPWMFlipCount = kPWMMaxCounter; - } // namespace -void SetupSquareWave(int pin_number) { +void SetupSquareWave(double frequency, int pin_number) { + // In conjunction with the PWM clock frequency, kPWMMaxCounter defines the + // frequency of the square wave. + const int max_count = 16e6 / frequency; + + // Since we want a duty cycle of 0.5, we flip the PVM output when the counter + // reaches kPWMMaxCounter / 2/; + const int flip_at_count = max_count / 2; + HwPWM0.addPin(pin_number); HwPWM0.setClockDiv(PWM_PRESCALER_PRESCALER_DIV_1); - HwPWM0.setMaxValue(kPWMMaxCounter); - HwPWM0.writePin(pin_number, kPWMFlipCount); + HwPWM0.setMaxValue(max_count); + HwPWM0.writePin(pin_number, flip_at_count); HwPWM0.begin(); } diff --git a/code/parasite/lib/parasite/pwm.h b/code/parasite/lib/parasite/pwm.h index b4d625c..a33dff5 100644 --- a/code/parasite/lib/parasite/pwm.h +++ b/code/parasite/lib/parasite/pwm.h @@ -6,9 +6,9 @@ namespace parasite { // This is a simple, single-channel PWM-based square wave generator. // This only ever works for a single pin. If you call this function // twice with different pin numbers, nothing good will come out of it. -// I am particularly proud of how well I resisted making this "generic" -// and "reusable". -void SetupSquareWave(int pin_number); +// I am particularly proud of how well I resisted making this generic +// and reusable. +void SetupSquareWave(double frequency, int pin_number); } // namespace parasite #endif // _PARASITE_PWM_H_ \ No newline at end of file diff --git a/code/parasite/src/main.cpp b/code/parasite/src/main.cpp index a370de6..24ab5ff 100644 --- a/code/parasite/src/main.cpp +++ b/code/parasite/src/main.cpp @@ -5,12 +5,13 @@ constexpr int kLED1Pin = 17; constexpr int kLED2Pin = 18; constexpr int kPWMPin = 19; +constexpr double kPWMFrequency = 500000; void setup() { Serial.begin(9600); pinMode(kLED1Pin, OUTPUT); pinMode(kLED2Pin, OUTPUT); - parasite::SetupSquareWave(kPWMPin); + parasite::SetupSquareWave(kPWMFrequency, kPWMPin); } void loop() {