Overview
A short Arduino code to cause an LED to blink. An easy application of the robust and relatively simply programming language.
Parts
-Arduino microcontroller and carrier board
-LiPo battery
-Optional: Light Emitting Diodes (LEDs)
-Optional: 10kOhm resistors
Prepare the breadboard
Not needed if you use the LED that is already on the Nano (i.e. Pin 13)!
Program the Microcontroller
/*** @file: blinking LED example* @date: 2/21/2011** @DESCRIPTION* blinks an LED every 1sec* use resistor with an LED if not using pin 13**/// include additional headers// none#define LED_PIN 13 // Pin 13 is an LED on most Arduino boards//--- Function: Setup ()void setup (){ pinMode (LED_PIN, OUTPUT); // enable pin 13 for digital output}//--- Function: loop ()void loop (){ digitalWrite (LED_PIN, HIGH); // turn on the LED delay (1000); // wait one second (1000 milliseconds) digitalWrite (LED_PIN, LOW); // turn off the LED delay (1000); // wait one second}Sometimes you need to do two things at once. For example you might want to blink an LED while reading a button press. In this case, you can't use delay(), because Arduino pauses your program during the delay(). If the button is pressed while Arduino is paused waiting for the delay() to pass, your program will miss the button press.
For more details: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
Program the Microcontroller
/* Blink without Delay http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay */// constants won't change. Used here to set a pin number :const int ledPin = 13; // the number of the LED pin// Variables will change :int ledState = LOW; // ledState used to set the LED
// Generally, you should use "unsigned long" for variables that hold time// The value will quickly become too large for an int to storeunsigned long previousMillis = 0; // will store last time LED was updated
// constants won't change :const long interval = 1000; // interval at which to blink (milliseconds)
void setup() {
pinMode(ledPin, OUTPUT); // set the digital pin as output:
}void loop() {
// here is where you'd put code that needs to be running all the time. // check to see if it's time to blink the LED; that is, if the // difference between the current time and last time you blinked // the LED is bigger than the interval at which you want to // blink the LED. unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
// save the last time you blinked the LED previousMillis = currentMillis; // if the LED is off turn it on and vice-versa: if (ledState == LOW) {
ledState = HIGH;
} else {
ledState = LOW;
} // set the LED with the ledState of the variable: digitalWrite(ledPin, ledState); }}