Exercise 1
Code a program that will control:
with button BTN1 on P7
Blinking a light without using delay():
If you are testing for a button press or some other event, a delay will interfere with your results. You can't use
delay(), or you'd stop everything else in the program while the LED blinked. Here's some code that demonstrates how to blink the LED without using
delay(). It keeps track of the last time it turned the LED on or off. Then, each time through
loop() it checks if a sufficient interval has passed - if it has, it turns the LED off if it was on and vice-versa.
Copy code and modify it. Wire your board and upload the program
/* Blinking LED without using delay*/
// LED should be the pin connected to an LED
int ledPin = ___;
// set value to the state of the LED before the program runs
int value1 = ___;
int value2 = ___;
// store last time LED was updated
long previousMillis = 0;
// interval at which to blink (milliseconds)
long interval = _____;
void setup(){
// sets the digital pin as output
_____________
}
void loop(){
// check to see if the difference between the current time and
//last time we blinked the LED bigger than
// the interval at which you want to blink the LED.
if (millis() - previousMillis > interval) {
// remember the last time you blinked the LED
//by setting previousMillis to millis()
_________________
// if the LED is off turn it on and vice-versa.
if (value1 == LOW){
value1 = ___;
value2 = ___;
}else{
value1 = ____;
value2 = ____;
}
digitalWrite(ledPin, value);
___________________________
}
}
Exercise 2—Fading up and down
Now you are going to wire your circuit and use a program to control an analog signal.
-
Connect an LED/resistor to pin 9 of your Arduino.
-
Connect two push buttons to your Arduino
-
In the main loop, write code that decrements a variable named value if one of the buttons is pressed, and increments the same variable if the other button is pressed
-
Set value to constrain(value, 0,255) What this does is prevents value from becoming a negative number or a number greater than 255.
-
call the method analogWrite() and pass it the led and value.
-
call delay() and pass it 10.
After you test the code and the circuit make the fade or brighten happen faster.