1
0

analogWriteExample.ino 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*
  2. Mega analogWrite() test
  3. This sketch fades LEDs up and down one at a time on digital pins 2 through 13.
  4. This sketch was written for the Arduino Mega, and will not work on previous boards.
  5. The circuit:
  6. * LEDs attached from pins 2 through 13 to ground.
  7. created 8 Feb 2009
  8. by Tom Igoe
  9. This example code is in the public domain.
  10. */
  11. // These constants won't change. They're used to give names
  12. // to the pins used:
  13. const int lowestPin = 2;
  14. const int highestPin = 33;
  15. #include <ESP32Servo.h>
  16. Servo myservo;
  17. void setup() {
  18. Serial.begin(115200);
  19. // Allow allocation of all timers
  20. ESP32PWM::allocateTimer(0);
  21. ESP32PWM::allocateTimer(1);
  22. ESP32PWM::allocateTimer(2);
  23. ESP32PWM::allocateTimer(3);
  24. }
  25. void loop() {
  26. if (!myservo.attached()) {
  27. myservo.setPeriodHertz(50); // standard 50 hz servo
  28. myservo.attach(33, 1000, 2000); // Attach the servo after it has been detatched
  29. }
  30. myservo.write(0);
  31. // iterate over the pins:
  32. for (int thisPin = lowestPin; thisPin <= highestPin; thisPin++) {
  33. if (ESP32PWM::hasPwm(thisPin) && // Is it possible for this pin to PWM
  34. (ESP32PWM::channelsRemaining() > 0 || // New channels availible to allocate
  35. pwmFactory(thisPin) != NULL || // already allocated this pin in the factory
  36. thisPin == 25 || // one of the 2 DAC outputs, no timer needed
  37. thisPin == 26)) { // one of the 2 DAC outputs, no timer needed
  38. if (pwmFactory(thisPin) == NULL) { // check if its the first time for the pin or its a DAC
  39. if (thisPin == 25 || // one of the 2 DAC outputs, no timer needed
  40. thisPin == 26) {
  41. Serial.println("DAC to pin " + String(thisPin));
  42. } else
  43. Serial.println("Writing to pin " + String(thisPin));
  44. pinMode(thisPin, OUTPUT);
  45. }
  46. // fade the LED on thisPin from off to brightest:
  47. for (int brightness = 0; brightness < 255; brightness++) {
  48. analogWrite(thisPin, brightness);
  49. delay(1);
  50. myservo.write(brightness);
  51. }
  52. // fade the LED on thisPin from brithstest to off:
  53. for (int brightness = 255; brightness >= 0; brightness--) {
  54. analogWrite(thisPin, brightness);
  55. myservo.write(brightness);
  56. delay(1);
  57. }
  58. }
  59. }
  60. myservo.detach(); // Turn the servo off for a while
  61. delay(2000);
  62. }