/* Changing duty cycle of PWM LED with a button. This was adapted from: http://www.arduino.cc/en/Tutorial/Debounce */ // constants won't change. They're used here to // set pin numbers: const int buttonPin = 3; // the number of the pushbutton pin const int ledPin = 7; // the number of the LED pin // Variables will change: int buttonState; // the current reading from the input pin int lastButtonState = LOW; // the previous reading from the input pin int toggle = 0; int buttonPressed; long lastDebounceTime = 0; // the last time the output pin was toggled long debounceDelay = 50; // the debounce time; increase if the output flickers void setup() { pinMode(buttonPin, INPUT); pinMode(ledPin, OUTPUT); } //duty cycles that we will have float duty[] = {0.,.1,.2,.4,1.0}; int which_duty = 0; int period = 10; //ms void loop() { digitalWrite(ledPin, HIGH); delay(duty[which_duty]*period); digitalWrite(ledPin, LOW); delay((1-duty[which_duty])*period); //check out the button to see if we need to switch duty cycle. buttonPressed = 0; int reading = digitalRead(buttonPin); if (reading != lastButtonState) { lastDebounceTime = millis(); } if ((millis() - lastDebounceTime) > debounceDelay) { buttonState = reading; } if(toggle == 0 && buttonState == 1){ which_duty = (which_duty+1) % 5; toggle = 1; } if(toggle == 1 && buttonState == 0){ toggle = 0; } lastButtonState = reading; }