In this lesson we show you how to create a Dimmable LED using two pushbuttons. Pressing one button will gradually increase the brightness, while pressing the other button will gradually decrease the brightness. The project also includes an active buzzer to provide the user feedback that either maximum or minimum brightness have been reached. I encourage you to try and build this yourself before watching the video. Then see if you can do it on your own, and then see if you are doing the way I do it, or if you find an alternative suitable solution.
If you want to follow along at home, you can order the Arduino Kit we are using HERE.
Below is the code we used to achieve the toggle operation. The video gives details on how to connect up the circuit.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | int buttonPin1=12; int buttonPin2=11; int buzzPin=2; int LEDPin=3; int buttonVal1; int buttonVal2; int LEDbright=0; int dt=500; void setup() { // put your setup code here, to run once: pinMode(buttonPin1,INPUT); pinMode(buttonPin2,INPUT); pinMode(LEDPin,OUTPUT); pinMode(buzzPin,OUTPUT); Serial.begin(9600); } void loop() { buttonVal1=digitalRead(buttonPin1); buttonVal2=digitalRead(buttonPin2); Serial.print("Button 1 = "); Serial.print(buttonVal1); Serial.print(", "); Serial.print("Button 2 = "); Serial.println(buttonVal2); delay(dt); if (buttonVal1==0){ LEDbright=LEDbright+5; } if (buttonVal2==0){ LEDbright=LEDbright-5; } Serial.println(LEDbright); if (LEDbright>255){ LEDbright=255; digitalWrite(buzzPin,HIGH); delay(dt); digitalWrite(buzzPin,LOW); Serial.println("Buzz HIGH"); } if (LEDbright<0){ LEDbright=0; digitalWrite(buzzPin,HIGH); delay(dt); digitalWrite(buzzPin,LOW); Serial.println("Buzz LOW"); } analogWrite(LEDPin, LEDbright); } |