Creating a schematic, circuit, and code that uses LEDs, a button, a for-loop, digitalWrite(), digitalRead(), and analogWrite().
I chose 220Ω for the resistors for my LEDs because I needed to find the optimal resistor to prevent broken LEDs. The reasoning is -- two(yellow, green) have 1.8 V drop. Current is 20 mA. Voltage from Arduino is 5V. Using Ohm’s law(V = I x R), the circulation to find R is:5V - 1.8V = 3.2 V = 0.02 (20mA) x R. R is 160Ω. And the resistors nearest value to 160Ω were 220Ω.
To prevent that current goes too high going into the ground pin, which would break the Arduino, the circuit needs a resistor for a push button. The maximum current allowed to go into the ground pin is 200mA. As current voltage is 5V, it needs at least 25 ohms of resistance. So I chose 100ohms for the push button resistor, which has nearest value to 25 ohms.
// the number of the pushbutton pin const int buttonPin = 2; // yellow led connected to pin 4 const int yellowLed = 4; // green led connected to pin 5 const int dimLed = 5; // variable for reading the pushbutton status int buttonValue = 0; // the higher the number, the slower the speed of blinking of yellow LED int timer = 500; // the setup function runs once when you press reset or power the board void setup() { // initialize yellow LED pin as an output pinMode(yellowLed, OUTPUT); // initialize pushbutton pin as an input pinMode(buttonPin, INPUT); } void loop() { //read the state of the pushbutton value: buttonValue = digitalRead(buttonPin); //check if the pushbutton is pressed. If pressed, buttonValue is High. if (buttonValue == HIGH) { //turn on yellow LED digitalWrite(yellowLed, HIGH); //wait for 0.5 seconds delay(timer); //turn off yellow LED digitalWrite(yellowLed, LOW); //fade in from min to max in increments of 5 points for (int fadeValue = 0 ; fadeValue <= 255; fadeValue += 5) { //sets the value (range from 0 to 255): analogWrite(dimLed, fadeValue); // wait for 20 milliseconds to see the dimming effect delay(20); } // fade out from max to min in increments of 5 points for (int fadeValue = 255 ; fadeValue >= 0; fadeValue -= 5) { //sets the value (range from 0 to 255): analogWrite(dimLed, fadeValue); //wait for 20 milliseconds to see the dimming effect delay(20); } //check if the pushbutton is pressed. If not, buttonValue is low and turn off the dim LED. } else { digitalWrite(dimLed, LOW); } }
Tada! Once clicked the push button, the yellow LED blinks for 0.5 seconds. Then, the green LED fades in and out smoothly.