BASIC CODE ELEMENTS
You just did some simple coding. Now you’ll explore some of the basic elements of the C language. Reopen the basic Blink example by clicking on the upward pointing arrow in the Toolbar and then selecting 01.Basics → Blink. Then, copy and paste the following example code into your Arduino window, replacing all of the code in your window with the code below:
/* Blink Turns on an LED for one second, then off for one second, repeatedly. This example code is in the public domain. */ // Pin 13 has an LED connected on most Arduino boards. // give it a name: int led = 13; // set the variable “led” to the value 13 // the setup routine runs once when you press reset: void setup() { // initialize the digital pin as an output. pinMode(led, OUTPUT); } void loop() { digitalWrite(led, HIGH); // turn the LED on delay(1000); // wait for a second digitalWrite(led, LOW); // turn the LED off delay(1000); // wait for a second }
Click on the check mark button in the Toolbar to compile the code. A “Done compiling” message should appear in the Status Bar. If you receive an error message instead, make sure your code matches the code above exactly. Continue to edit and compile until you receive a “Done compiling” message.
There are three code elements in the Blink example: comments, variables, and simple statements.
COMMENTS
The first few lines of the Blink example are a comment, a piece of text that will be ignored by the computer when the code is compiled.
/*
Blink
Turns on an LED for one second, then off for one second, repeatedly.
This example code is in the public domain.
*/
You can use comments to make notes—for yourself and others—in your programs. Comments are a very useful way to document what a program is for. When you come back to a program long after you wrote it, comments let you quickly understand what it does. Comments are shown in a greyish brown in the Arduino environment. Notice how the comments in the example code describe what different parts of the program do.
Any block of text between /* and */ characters is a comment. Anything written on a line after two slash characters // is also a comment. The two slash characters can only create comments that are a single line long. You can add comments anywhere and they won’t change a program’s behavior. Arduino will automatically color them grey. Generally, you should use comments to help you remember what different parts of a program do.
Try adding your own comment to the code and uploading the new program to the LilyPad. The example here shows a single-line comment.
// Mary had a little lamb, little lamb, little lamb...
// Pin 13 has an LED connected on most Arduino boards.
// give it a name:
Comments can also be useful when you want to temporarily remove a piece of code from your program. For example, if you put // in front of the digitalWrite(led, LOW); line in your program, that line is skipped when you compile and upload the code to the LilyPad. This is called commenting out pieces of code. Try making this edit and then compiling and uploading the code. What happens? Look at the new code carefully. Can you see why the LED’s behavior has changed?
void loop() { digitalWrite(led, HIGH); // turn the LED on delay(500); // wait for a half second // digitalWrite(led, LOW); // turn the LED off delay(500); // wait for a half second }
Remove the // you put in front of the the digitalWrite(led, LOW); line. Compile and upload your code so that your LED blinks again.
VARIABLES
Writing a program is a lot like writing a cooking recipe. When you write a recipe there is a basic structure that you follow. You list out the ingredients at the beginning of the recipe and you write instructions in the order that they need to be executed. (You don’t, for instance, tell a cook to put his pie in the oven before you explain how to make dough for the crust.)
When you write a program you also write instructions in the order that they need to be carried out and list “ingredients”—pieces of code that you’ll use in the rest of your program—at the top of your file. A computer, like a good cook, will read and carry out a program in the order it’s written.
Variables in a program are like ingredients in a recipe. They are generally listed at the beginning of a program and they identify the components that the program will be using and controlling. After the comment at the top of the program, the next section of the Blink code looks like the block below.
// Pin 13 has an LED connected on most Arduino boards. // give it a name: int led = 13; // set the variable “led” to the value 13
The first two lines in this section are comments. The third line, int led = 13;, creates a variable called led. This line is called a variable declaration statement. It declares a variable called led and initializes it to 13, identifying the critical ingredient of the Blink program, the LED. The green LED on the LilyPad board is connected to pin 13 on the LilyPad’s microcontroller. The line int led = 13; allows you to use the word led instead of the number 13 to refer to the LilyPad’s built-in LED in your program. This makes the program much easier to write and understand. You don’t need to remember a number, you can use a meaningful name instead.
When you create a variable you set aside a chunk of memory in the LilyPad and give it a name. The int led = 13; line creates a variable called led and stores the value 13 in that memory. There are different types of variables in the same way that there are different types of computer files. Computer file types are distinguished by suffixes (ie: .docx, .pdf, .jpg, etc.). Variable types are specified by prefixes when they’re created. In the example above, the text int describes what type of variable led is. int stands for integer, which means a whole number. Almost all of the variables you will use in your Arduino programs will be of type int.
A variable declaration statement can be broken down like so: Any line of code that creates and assigns a value to a variable has this same basic structure.
When the program is running, after it’s compiled and uploaded, whenever the LilyPad finds the variable led it replaces it with the number 13. What looks like this to you now:
digitalWrite(led, HIGH); // turn the LED on delay(1000); // wait for a second digitalWrite(led, LOW); // turn the LED off delay(1000); // wait for a second
Will look like this to the LilyPad when the program is running:
digitalWrite(13, HIGH); // turn the LED on delay(1000); // wait for a second digitalWrite(13, LOW); // turn the LED off delay(1000); // wait for a second
To begin to understand why variables are useful, add one to your program. Add a variable called delayTime to your program and set its value to 1000. Add this line right after the int led = 13; line.
Now, replace every delay(1000); line in your program with delay(delayTime);. Also change the comments to correspond to your new code. Compile this code and upload it to your LilyPad. The LED should blink every second, just like before.
// Pin 13 has an LED connected on most Arduino boards. // give it a name: int led = 13; // set the variable “led” to the value 13 int delayTime = 1000;
void loop() { digitalWrite(led, HIGH); // turn the LED on delay(delayTime); // wait for delayTime digitalWrite(led, LOW); // turn the LED off delay(delayTime); // wait for delayTime }
Now try changing the initial value of delay time from 1000 to 500, by editing the int delayTime = 1000; line. Compile this code and upload it to your LilyPad. What happens to the behavior of your LED? Experiment with other values for delayTime, compiling and uploading the code each time you change it.
Notice how you only have to change one line in your program to change the speed of the LED’s blinking. Before, when you changed the timing in your code, you had to change at least two lines.
Variables help you keep track of the critical features (ingredients) of your code. When you use a variable, all of the important information about it—its name, type and value—is listed once at the beginning of the program where it can be easily and quickly changed.
If you would like to save the changes you made to your code, click on the downward pointing arrow in the Toolbar. Click “OK” on the popup window that appears and choose an appropriate name for your file. Click on the “Save” button to complete the process.
SIMPLE STATEMENTS
Begin this next section with a fresh version of the Blink program. Reopen the Blink example by clicking on the upward pointing arrow in the Toolbar and then selecting 01.Basics → Blink. Then, copy and paste the following example code into your Arduino window, replacing all of the code in your window with the code below:
/* Blink Turns on an LED for one second, then off for one second, repeatedly. This example code is in the public domain. */ // Pin 13 has an LED connected on most Arduino boards. // give it a name: int led = 13; // set the variable “led” to the value 13 // the setup routine runs once when you press reset: void setup() { // initialize the digital pin as an output. pinMode(led, OUTPUT); } void loop() { digitalWrite(led, HIGH); // turn the LED on delay(1000); // wait for a second digitalWrite(led, LOW); // turn the LED off delay(1000); // wait for a second }
Click on the check mark button in the Toolbar to compile the code. A “Done compiling” message should appear in the Status Bar. If you receive an error message instead, make sure your code matches the code above exactly. Continue to edit and compile until you receive a “Done compiling” message.
Statements are essentially computer-sentences— lines of code that tell the computer to do something. The line of code digitalWrite(led, HIGH); is an example of a simple statement. All simple statements end with a semicolon (;) in the same way that all sentences end with a period. Your code is full of simple statements. Here are a few:
digitalWrite(led, HIGH);
int led = 13;
delay(1000);
Each of these lines tells the computer to do something. Each ends with a semicolon. Note that a comment to the right of each statement in your program tells you what each one does.
Try deleting the semicolon at the end of the int led = 13; line. Compile your code. What happens? Do you see an error message?
When you’re writing your own code it’s easy to forget to put a semicolon at the end of a statement, but the Arduino software will not compile or upload your code until it is perfectly punctuated.
Errors like missing semicolons can be tricky to find and fix, but Arduino does try to help you. Notice how the cursor in Arduino jumped to the line immediately following the int led = 13; line when you compiled the code. This is a clue about the location of the error. The other clue is in the cryptic message that appears in the Feedback Area: Blink:13: error: expected ‘,’ or ‘;’before ‘void’.
Notice how the message says “expected ‘,’ or ‘;’“. It’s telling you that the error might be a missing semicolon. You’ll slowly learn to make more sense of the strange error messages!
Replace the semicolon at the end of the int led = 13; line and recompile your code.
Next try introducing a different kind of error into your program. In the loop section, delete the W from the first digitalWrite(led, HIGH); statement so that it reads digitalrite(led, HIGH);. Try compiling your code. What happens?
Code needs to be perfectly spelled, capitalized, and punctuated before it will compile! In the case of misspellings and mis capitalizations, Arduino gives you some extra help. Notice how the text changed from orange to black when you changed the digitalWrite(led, HIGH); statement. Try changing the word LOW on the third line to low. The text color should change from blue to black.
digitalrite(led, HIGH); // turn the LED on delay(1000); // wait for a second digitalWrite(led, low); // turn the LED off delay(1000); // wait for a second
Arduino gives special colors to all of its built-in procedures and variables. When you misspell or mis-capitalize one of these key words, this coloring will disappear. Unfortunately, if you misspell or mis-capitalize any other part of a program—a variable that you created, say—you won’t get any color clues to help you find your mistake.
Experiment with other misspellings and mis-capitalizations, recompiling your code after each edit, to see what kind of feedback you get in different situations. When you’re done experimenting, correct your code and recompile it.
void loop() { digitalWrite(led, HIGH); // turn the LED on delay(1000); // wait for a second digitalWrite(led, LOW); // turn the LED off delay(1000); // wait for a second digitalWrite(led, HIGH); // turn the LED on delay(500); // wait for half a second digitalWrite(led, LOW); // turn the LED off delay(500); // wait for half a second }
To experiment with writing your own statements you’re now going to create an uneven blink pattern. Modify the program so that the LED:
• turns on for 1 second
• turns off for 1 second
• turns on for half a second
• turns off for half a second
Add four statements to your code to achieve this behavior.
Compile and upload this new program to your LilyPad and see what happens. Notice how the additional statements change the blinking pattern. Try adding, removing, or editing statements of your own to get different patterns. You might also try experimenting with using variables like delayTime to control these patterns. Once you’ve created a blinking pattern you’re happy with, click on the downward pointing arrow in the Toolbar to save your changes. Click “OK” on the popup window that appears and choose a name for your file. Click on the “Save” button to complete the process.