In lesson 27 we learned how to incorporate a pushbutton into an arduino project. We learned how to utilize pull-up and pull-down resistors in order to incorporate a button into a circuit. The operation of the button in lesson 27 was pretty simple . . . if the button was held down, the LED would come on. When the button was released, the LED would turn back off. This is an interesting demonstration, but much more interesting is the case where we make a toggle switch. If you press and release the button, the LED comes on, and then if you press and release the button again, the LED goes off. While this sounds very similar to the previous case, it turns out to require a lot more thought. This video lesson explains how to think about this problem, and how to make it work.
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 | int LEDState=0; int LEDPin=8; int buttonPin=12; int buttonNew; int buttonOld=1; int dt=100; void setup() { // put your setup code here, to run once: Serial.begin(9600); pinMode(LEDPin, OUTPUT); pinMode(buttonPin, INPUT); } void loop() { buttonNew=digitalRead(buttonPin); if(buttonOld==0 && buttonNew==1){ if (LEDState==0){ digitalWrite(LEDPin,HIGH); LEDState=1; } else{ digitalWrite(LEDPin, LOW); LEDState=0; } } buttonOld=buttonNew; delay(dt); } |