Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Fade
- This example shows how to fade an LED on pin 9 using the analogWrite()
- function.
- The analogWrite() function uses PWM, so if you want to change the pin you're
- using, be sure to use another PWM capable pin. On most Arduino, the PWM pins
- are identified with a "~" sign, like ~3, ~5, ~6, ~9, ~10 and ~11.
- This example code is in the public domain.
- http://www.arduino.cc/en/Tutorial/Fade
- */
- #include <PWM.h>
- //use pin 11 on the Mega instead, otherwise there is a frequency cap at 31 Hz
- int led = 3; // the pin that the LED is attached to
- // how many points to fade the LED by
- int32_t frequency = 25000; //frequency (in Hz)
- const int sensePin = 2;
- void setup()
- {
- Serial.begin(9600);
- //initialize all timers except for 0, to save time keeping functions
- InitTimersSafe();
- //sets the frequency for the specified pin
- bool success = SetPinFrequencySafe(led, frequency);
- //if the pin frequency was set successfully, pin 13 turn on
- if(success) {
- pinMode(13, OUTPUT);
- digitalWrite(13, HIGH);
- }
- pinMode(sensePin, INPUT_PULLUP);
- attachInterrupt(digitalPinToInterrupt(sensePin), sense, RISING);
- }
- int brightness = 5; // how bright the LED is
- int fadeAmount = 5; // how many points to fade the LED by
- unsigned int skipAdjust = 0;
- unsigned long lastPulse = 0;
- volatile unsigned long pulsus = 0;
- void sense() {
- pulsus++;
- }
- // the loop routine runs over and over again forever:
- void loop() {
- // set the brightness of pin 9:
- pwmWrite(led, brightness);
- // change the brightness for next time through the loop:
- if(skipAdjust != 0) {
- skipAdjust--;
- } else {
- brightness = brightness + fadeAmount;
- // reverse the direction of the fading at the ends of the fade:
- if (brightness <= 5 || brightness >= 255) {
- fadeAmount = -fadeAmount;
- skipAdjust = 10;
- }
- }
- unsigned long currentTime = millis();
- unsigned long pulses = pulsus;
- unsigned long freq = currentTime == lastPulse ? 0 : ( pulses * 1000 / (currentTime - lastPulse));
- pulsus -= pulses;
- lastPulse = currentTime;
- Serial.print(brightness);
- Serial.print(' ');
- Serial.print(freq);
- Serial.println();
- // wait for 50 milliseconds to see the dimming effect
- delay(1000);
- }
Add Comment
Please, Sign In to add comment