|
| 1 | +#include <PWM.h> |
| 2 | + |
| 3 | +// Pin configuration |
| 4 | +int led = 9; // LED pin |
| 5 | +int brightness = 127; // Initial brightness value for the PWM duty cycle |
| 6 | +float frequency = 60.3; // Initial frequency in Hz |
| 7 | + |
| 8 | +void setup() |
| 9 | +{ |
| 10 | + Serial.begin(9600); |
| 11 | + |
| 12 | + // Initialize all timers except for timer0 to save timekeeping tasks |
| 13 | + InitTimersSafe(); |
| 14 | + |
| 15 | + // Set the initial PWM frequency and duty cycle |
| 16 | + if (SetPinFrequencySafe(led, frequency)) |
| 17 | + { |
| 18 | + pwmWrite(led, brightness); |
| 19 | + Serial.println("PWM frequency and initial duty cycle set."); |
| 20 | + } |
| 21 | + else |
| 22 | + { |
| 23 | + Serial.println("Failed to set frequency."); |
| 24 | + } |
| 25 | +} |
| 26 | + |
| 27 | +void loop() |
| 28 | +{ |
| 29 | + if (Serial.available()) |
| 30 | + { |
| 31 | + // Read frequency and duty cycle values over Serial |
| 32 | + String inputString = Serial.readStringUntil('\n'); // Read string input until newline |
| 33 | + inputString.trim(); // Remove any extraneous spaces or newlines |
| 34 | + int freqDutySplitIndex = inputString.indexOf(','); |
| 35 | + |
| 36 | + if (freqDutySplitIndex != -1) |
| 37 | + { |
| 38 | + String freqStr = inputString.substring(0, freqDutySplitIndex); // Extract frequency string |
| 39 | + String dutyStr = inputString.substring(freqDutySplitIndex + 1); // Extract duty cycle string |
| 40 | + |
| 41 | + // Parse floats |
| 42 | + float newFrequency = freqStr.toFloat(); |
| 43 | + int newDutyCycle = dutyStr.toInt(); |
| 44 | + |
| 45 | + // Validate frequency range |
| 46 | + if (newFrequency >= 1 && newFrequency <= 2000000) |
| 47 | + { |
| 48 | + // Set the PWM frequency and apply duty cycle |
| 49 | + if (SetPinFrequencySafe(led, newFrequency)) |
| 50 | + { |
| 51 | + brightness = map(constrain(newDutyCycle, 0, 100), 0, 100, 0, 255); |
| 52 | + pwmWrite(led, brightness); |
| 53 | + Serial.print("Set frequency to: "); |
| 54 | + Serial.print(newFrequency); |
| 55 | + Serial.print(" Hz, duty cycle to: "); |
| 56 | + Serial.print(newDutyCycle); |
| 57 | + Serial.println("%"); |
| 58 | + } |
| 59 | + else |
| 60 | + { |
| 61 | + Serial.println("Failed to set new frequency."); |
| 62 | + } |
| 63 | + } |
| 64 | + else |
| 65 | + { |
| 66 | + Serial.println("Invalid frequency value."); |
| 67 | + } |
| 68 | + } |
| 69 | + else |
| 70 | + { |
| 71 | + Serial.println("Invalid input format. Use frequency,dutycycle (e.g., 60,50)."); |
| 72 | + } |
| 73 | + } |
| 74 | +} |
0 commit comments